Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Long list of if statements in Java

Sorry I can't find a question answering this, I'm almost certain someone else has raised it before.

My problem is that I'm writing some system libraries to run embedded devices. I have commands which can be sent to these devices over radio broadcasts. This can only be done by text. inside the system libraries I have a thread which handles the commands which looks like this

if (value.equals("A")) { doCommandA() } else if (value.equals("B")) { doCommandB() }  else if etc.  

The problem is that there are a lot of commands to it will quickly spiral to something out of control. Horrible to look out, painful to debug and mind boggling to understand in a few months time.

like image 907
Steve Avatar asked Jul 29 '09 11:07

Steve


People also ask

How do you handle multiple If statements in Java?

When using multiple conditions, we use the logical AND && and logical OR || operators. Note: Logical AND && returns true if both statements are true. Logical OR || returns true if any one of the statements is true.

How many types of IF statements are there in Java?

In Java, there are two forms of conditional statements: • the if-else statement, to choose between two alternatives; • the switch statement, to choose between multiple alternatives.


2 Answers

using Command pattern:

public interface Command {      void exec(); }  public class CommandA() implements Command {       void exec() {           // ...       } }  // etc etc 

then build a Map<String,Command> object and populate it with Command instances:

commandMap.put("A", new CommandA()); commandMap.put("B", new CommandB()); 

then you can replace your if/else if chain with:

commandMap.get(value).exec(); 

EDIT

you can also add special commands such as UnknownCommand or NullCommand, but you need a CommandMap that handles these corner cases in order to minimize client's checks.

like image 123
dfa Avatar answered Sep 19 '22 03:09

dfa


My suggestion would be a kind of lightweight combination of enum and Command object. This is an idiom recommended by Joshua Bloch in Item 30 of Effective Java.

public enum Command{   A{public void doCommand(){       // Implementation for A     }   },   B{public void doCommand(){       // Implementation for B     }   },   C{public void doCommand(){       // Implementation for C     }   };   public abstract void doCommand(); } 

Of course you could pass parameters to doCommand or have return types.

This solution might be not really suitable if the implementations of doCommand does not really "fit" to the enum type, which is - as usual when you have to make a tradeoff - a bit fuzzy.

like image 42
jens Avatar answered Sep 21 '22 03:09

jens