jeudi 19 novembre 2020

c# pattern to avoid using switch statement for repeated similar logic

I have a c# application where I need to return translated keypair value for different views.

For example, these are some of my views:

  • login
  • admin account
  • admin settings
  • admin employee
  • admin holiday
  • and so on.

Then every view call the same method for returning a dictionary of translation strings.

public ActionResult GetTranslations(string viewName)
    {
        
        // THIS IS A SAMPLE OF HOW TO GET THE TRANSLATIONS

        Dictionary<string, string> translations = new Dictionary<string, string>
        {
            { "usernamerequired", HttpContext.GetText("The user name is required","") },
            { "passrequired", HttpContext.GetText("The password is required", "") },
        };

        string json = JsonConvert.SerializeObject(points, Formatting.Indented);

        var response = new JsonResponse
        {
            data = translations ,
            message = "",
            num = 0,
            success = true,
            code = null
        };

        return Json(response, JsonRequestBehavior.AllowGet);
    }

So in order to avoid using "n" amount of Switch statements like:

Dictionary<string, string> translations = null;

switch(viewName)
{
   case "login":

     // specific translation for login
      translations = new Dictionary<string, string>
        {
            { "usernamerequired", HttpContext.GetText("The user name is required","") },
            { "passrequired", HttpContext.GetText("The password is required", "") },
        };

     break;

    // HERE OTHER CASES FOR THE OTHER VIEWS
}

Instead I would like to use a cleaner way, I was thinkin on having an interface like:

// Interface
interface ITranslation
{
  Dictionary<string, string> GetViewTranslations(); 
}

// Login  translation class
class LoginTranslation: ITranslation
{
  public Dictionary<string, string> GetViewTranslations()
  {
    // here the dictrionary generation code..
  }
}

// Admin Settings translation class
class AdminSettingsTranslation: ITranslation
{
  public Dictionary<string, string> GetViewTranslations()
  {
    // here the dictrionary generation code..
  }
}

Of maybe there is a better and cleaner way, any advice or clue?

Aucun commentaire:

Enregistrer un commentaire