Reputation: 1287
I have method which returns sql query as string. This method consider parameter 'level' , based on this parameter there are multiple if else statement like
if(level.equals("A1")){
// add some field in query
}
else if (level.equals("A2"))
{
// add some field and logic in query
}
..
so on
In future number of levels are going to increase and I don`t want to write pesky if else statements so I am looking for cleaner and maintainable design approach for this scenario. I am thinking of strategy design pattern but not sure whether it is best for this scenario.
Upvotes: 0
Views: 356
Reputation: 1073968
You have several options:
if
/else if
as you've indicated.
A Map
with the keys being the level string and the values being references of a functional interface type (Runnable
or an appropriate interface from java.util.function
, or your own) you can initialize with method references, lambdas, anonymous class instances, or even concrete class instances as required.
Here's an example of that last option, using the most basic functional interface, Runnable
, with method references:
import java.util.Map;
import java.util.HashMap;
public class Example {
private Map<String, Runnable> handlers;
public Example() {
this.handlers = new HashMap<String, Runnable>();
this.handlers.put("A1", this::a1action);
this.handlers.put("A2", this::a2action);
}
private void a1action() {
System.out.println("Action A1");
}
private void a2action() {
System.out.println("Action A2");
}
public void handleAction(String action) {
Runnable handler = this.handlers.get(action);
if (handler == null) {
System.out.println("No handler for '" + action + "'");
} else {
handler.run();
}
}
public static void main(String[] args) throws Exception {
Example ex = new Example();
ex.handleAction("A1");
ex.handleAction("A2");
ex.handleAction("A3");
}
}
Upvotes: 1
Reputation: 65793
You can use an enum
to list the operations and use valueOf
to work out which to use.
enum Levels {
A1 {
@Override
void doSomethingToTheQuery(Query q) {
// add some field in query
}
},
A2{
@Override
void doSomethingToTheQuery(Query q) {
// add some field and logic in query
}
};
abstract void doSomethingToTheQuery(Query q);
}
public void test() {
// Lookup the level and do hack the query.
Levels.valueOf("A1").doSomethingToTheQuery(q);
}
You can then add new levels just by adding to the enum
.
Upvotes: 0