I have C# application
that stores data in a NoSQL database
. The app has a repository class that uses a series of objects to translate the data from the NoSQL form to that used by the C# models, and vice versa (essentially a form of ORM). The objects implement a converter
interface, and each object works on one specific data type (string, bool, etc)
. Internally they use reflection to perform the transformation. Instances of these objects are created by a method that returns the object for the given type. Currently the logic looks something like the following:
if(type == typeof(string)
return new StringConverter(...);
if(type == typeof(int) || type == typeof(uint))
return new IntegerConverter(...);
... // and so on
However all those if
statements bother me. I know I could do something like create a dictionary to map types to creation methods but I am not sure if this will result in more readable, easy to maintain/extend code(?). Given the need to create the type abstractions what is the best way to go about doing this? Any suggestions welcomed. Huge thanks in advance.
Ideally, nested if-statements
are what you want to avoid. I am quoting Microsoft's Complete Code book. The idea is when you nest up to 3 levels, the attention of the developer maintaining the code or yours as the developer decreases drastically.
In your case, if your logic has to be hardcoded, there is no way around having a sequence of if-statements. However a smart way around it would be to follow the Factory design pattern.(Gangs of Four)