Users can have a Cookie called lang that contains either the value "default=1" (English) or "default=2" (French). This cookie is used to determine their preferred language. I have a function that needs to take the cookie and return the language has an Enum. If the cookie doesn't exist, I want to return English. I cannot change the cookie value.

Language enum:

  Public Enum Language
     Undefined = 0
     English = 1
     French = 2
  End Enum


  Public Function GetLangFromCookie() As Language
     If HttpContext.Current.Request.Cookies.Get("lang") IsNot Nothing Then
        Dim langCookie = HttpContext.Current.Request.Cookies.Get("lang").Value
        Return If(langCookie(langCookie.Length - 1) = "1", Language.English, Language.French)
     End If
     Return Language.English
  End Function

I feel like this is not efficient and not secure but I don't know how to improve it. Any suggestions?


1 Answer 1

  • You query HttpContext.Current.Request.Cookies.Get("lang") twice. Access it once and store it in a variable.
  • You will get a problem if in the future you have to support more than 9 languages. Instead of accessing the last char from langCookie you should Split() langCookie by = and take the second array element. You can then use [Enum].TryParse() to get the enum.
  • Some horizontal spacing (new lines) would help to easier read the code.

Your code could look like so

Public Function GetLangFromCookie() As Language

    Dim langCookie = HttpContext.Current.Request.Cookies.Get("lang")

    If langCookie Is Nothing Then
        Return Language.English
        Return GetLanguage(langCookie.Value)
    End If

End Function

Private Function GetLanguage(languageCookieValue As String) As Language

    Dim splittetCookieValue As String() = languageCookieValue.Split(New String() {"="}, StringSplitOptions.RemoveEmptyEntries)

    Dim languageIdentifier As String = splittetCookieValue.LastOrDefault()

    Dim foundLanguage As Language

    ' We don't care about the success of the TryParse() call
    [Enum].TryParse(Of Language)(languageIdentifier, foundLanguage)

    ' because foundLanguage will be 0 if it doesn't succeed and will be checked here
    Return If(foundLanguage = Language.Undefined, Language.English, foundLanguage)

End Function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.