I have an object with has two properties: Text and Type.
To avoid hard-coding the Types, I put them in the database, so they can be added to in future. At the moment the types are URL, Username and ID.
However, I now want to run a Utility method to clean up the object’s Text field based on which Type the object is (e.g. add ‘http://’ if its a URL).
Is there a way to do this in the Utilities class without hard-coding the types in a switch statement/if else block.
switch (type)
{
case 1:
TidyUrl();
case 2:
TidyUsername();
case 3:
TidyID();
default:
break;
}
In this example I’m hardcoding the IDs from the database (‘Type’ table), which can never be a good thing!
Is there a better way to do this?
Traditionally this is handled using a common interface, and dynamically constructing a concrete implementation to do the actual work.
for example:
then the implementations
And so on for the other types of tidying. Now you need a way of instantiating the right concrete class (
UrlTidy,IdTidyetc) from the type you are looking at. One way to do this might be to put the class name in the database along side the type, and use reflection to instantiate the right implementation ofITidy. Another wat would be to have aFactoryclass which uses some other method to instantiate the rightITidybased on type.