-3

I have a class called SomethingProvider that contains:

private static string convertMapA(string convertA)
    {
        switch (convertA?.ToUpper())
        {
            case "NONE":
            case "TEST":
            case "MEHTEST":
                return "None";
            case "MEH":
                return "meh";
            case "DAY":
            case "SOMEDAY":
                return "da";
            case "CON":
            case "C":
                return "cd";
            default:
                return convertA;
        }
    }
private static string convertMapB(string convertB)
{
    switch (convertB?.ToUpper())
    {
        case "ANNY":
        case "ANYU":
        case "BLAH":
            return "something";
        default:
            return convertB;
    }
}

There can be multiple versions of this class, I.e ClassAlphaProvider, ClassBetaProvider. Each method Convert will have slightly different mappings dependent on its class.

And to make it more interesting there are multiple Projects, with multiple classes, with these convertMapping methods that alter per class.

Now, I was considering, dictionary mapping instead or, implement strategy pattern but feels overkill for strings mapping? Maybe even Db implementation of sorts?

What would be a good approach to refactoring this?

NOTE: the case statements change frequently. trying to consider open/close with the idea that the case statements change a lot.

lemunk
  • 105

2 Answers2

0

Switch statements for mapping aren't terrible. Switch statements for string to string mapping sounds like there is a hidden enum/record type that should exist instead. If you have multiple different mappings for different objects across multiple different projects, that is fine. If you have multiple different mappings for functionally the same object, that is bad. In the latter case you are better off consolidating to a single library and sharing it across projects, it's better to have the hard link that can be tracked than no link.

Ryathal
  • 13,486
  • 1
  • 36
  • 48
0

It sounds like these mappings are not really part of the functionality of your code but application configuration data. If they change frequently and don't influence the code path but just determine some output strings I would really recommend putting them into some configuration datastore or a database table. That makes maintenance much more flexible.

If the mappings can have common and individual parts depending on class and project, the configuration data structure probably needs to be a bit more complex, with generic mappings and overrides (and probably override precedence rules when you have multiple dimensions in which the mappings can be specialized, such as the named projects and classes).

It is also quite possible that you've got an XY problem here, and it would be helpful to know the real use case for these mappings instead of some abstract "meh"/"blah"/"something".