I am writing a code where I need to write lot of switch cases and each case has some business logic which basically is a query from mysql db query. i.e.
String computeResult()
{
//code to connect to mysql
switch(x)
{
case A:
//executing some query and return the result after some processing
case B:
//executing some query and return the result after some processing
//15 more such cases ahead...
}
}
I am writing this code in java, which is an object oriented language. I looked into the following options: Option 1: Writing the whole business logic into 15 seperate methods in the same class, but then I am going the procedural language way. Option 2: Applying strategy pattern. and create a base class with common code, and then various different strategies each computing a result for a single case. The calls to methods of those classes are still present in the computeResult()
method. But this will call for a class explosion, 15 more classes will be added to my project. Later if I need to add some more cases, that means adding some more classes, and adding some more case statments in computeResult()
method. I dont know any way in which that switch case code can be avoided, that is a hardcoded thing, at max I can put these case name to class mapping in a constants file. For example:
HashMap < String, BaseResultComputer > map
which will just map the case names to the respective result computer implementations. So whenever we add one more implementation, we just add one more class, and have to change in that constants file. Please suggest what is the best design to handle this.
Aucun commentaire:
Enregistrer un commentaire