Question

I've the following class

public static class Translation
{
    public enum LanguageCultureName
    {
        enGB,
        zhCN
    };

   public static string Get(LanguageCultureName languageCultureName, string sValue)
   {
        if (languageCultureName == LanguageCultureName.enGB)
        {
            return sValue;
        }
        else
        {
            //get translated string
            return ....
        }
   }
}

Basically I'm looking to call the method like

Is it preferable to put an inline If statement around the method call like;

LanguageCultureName languageCultureName = LanguageCultureName.zhCN;
string sTranslation = languageCultureName == LanguageCultureName.enGB ? "My String to translate" : Translation.Get(languageCultureName, "My String to translate");

,or just call it, and if it is enGB return the passed string like

LanguageCultureName languageCultureName = LanguageCultureName.zhCN;
string sTranslation = Translation.Get(languageCultureName, "My String to translate");

Are there any performance reasons for this, or is it personal preference ?

Was it helpful?

Solution

This is abstraction that should happen inside the Get method, not inlined.

LanguageCultureName languageCultureName = LanguageCultureName.zhCN;
string sTranslation = Translation.Get(languageCultureName, "My String");

I should also note that having the enGB strings hardcoded is not a good practice. You should move both the enGB and zhCN strings to external resources files (e.g. .resx).

OTHER TIPS

I would go with the second one. There will be very little performance impact but it is more readable.

The way I understand your code is that you want check if the culture is already in English or not and return the standard string if it is instead of translating it. In order for this to make a performance impact you have to take a few aspects in account

  • How often do you expect the culture to be in English?
  • How intensive is the translating operation?
  • Can you pass around a non-english string as input?

Each of these remarks will have influence over your eventual design. You seem to be entertaining the thought of removing the english if altogether and replace it with a ternary statement, aka: removing an if and adding an if in the wrong place.

And having considered all that: if your validation whether or not it's an english culture is the first statement inside your method, there will never be a notable difference between that and putting it outside in the ternary statement.

Let's not forget one of the ten comandments:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top