Using Java Map rather than if and else (Actually this more appropriate for switch case)
Actually this idea is not such a big stuff rather just find small thing that I found so interesting.
Usually we using if else or maybe switch to create logical condition until some extend the condition became so unreadable because its to long, for example
public class RobotSays{
private void saysHello(){
System.out.println("Hallooo Human");
}
private void saysGood(){
System.out.println("I am Good, Human");
}
private void saysFine(){
System.out.println("Technically I am Fine, Human");
}
public void robotSaysSomething(String says){
if(says.equals("Hello")){
saysHello();
}else if(says.equals("Good")){
saysGood();
}else if(says.equals("Fine")){
saysFine();
}
}
}
Look bit tedious work especially if the condition continue until very long. How about using Map
public class RobotSays{
private Map<String,Method> mm = new HashMap<String,Method>();
private void saysHello(){
System.out.println("Hallooo Human");
}
private void saysGood(){
System.out.println("I am Good, Human");
}
private void saysFine(){
System.out.println("Technically I am Fine, Human");
}
public void robotSaysSomething(String says){
mm.put("Hello",RobotSays.class.getMethod("saysHello"));
mm.put("Good",RobotSays.class.getMethod("saysGood"));
mm.put("Fine",RobotSays.class.getMethod("saysFine"));
mm.get(says).invoke(null);
}
}
Haha I don’t know whether this alternative is solution or disaster but you can try. Happy Coding
2
Kudos
2
Kudos