Truth Table with Actions

In my code, I evaluate 3 booleans.
Each combination of these booleans truth values ​​requires different actions (for example, a different method must be executed).
I am currently using if-else block (8 options, not so good). I am wondering if there is another way to write this code that will make it “prettier”.
Maybe a design template?
Does anyone have an idea?

+5
source share
4 answers

I suggest you use the command template .

public interface Command {
     void exec();
}

public class CommandA() implements Command {

     void exec() {
          // ... 
     }
}

Create a Map object and populate it with Command instances:

Then you can do something like this in your iteration on the map.

commandMap.get(value).exec();
+3
source

switch ((A?4:0) + (B?2:0) + (C?1:0)){
case  0: //A,B,C false 
break;

case  3: //A False, B,C true
break;

case  4: //A True, B,C false 
break;
}
+3

The three elements are not so bad, but what if your table contained 4 or 5 or 25? May get complicated. Here is a compact technique that some will find useful while others will shoot.

Build a row of table elements:

final boolean a = false, b = false, c = false;
final String method = "state"+(a?"AT":"AF")+(b?"BT":"BF")+(c?"CT":"CF");

This leads to the following lines:

// stateAFBFCF
// stateAFBTCF
// stateAFBFCT
...

Create methods with the same name to handle each combo state:

public void stateAFBTCF() { }
public void stateAFBTCF() { }
public void stateAFBFCT() { }
...

Use reflection to invoke the correct method:

final Class<?> _class = handler.getClass();
final Method _method = _class.getDeclaredMethod(methodName, new Class[] {});
_method.invoke(handler, new Object[] { });
+1
source

If you have as many methods as possible combinations, you can check combinations when entering different methods:

public void a(boolean a, boolean b, boolean c) {
    if (a && !b && !c) {
    }
}

public void ab(boolean a, boolean b, boolean c) {
    if (a && b && !c) {
    }
}

public void abc(boolean a, boolean b, boolean c) {
    if (a && b && c) {
    }
}

public void ac(boolean a, boolean b, boolean c) {
    if (a && !b && c) {
    }
}

public void b(boolean a, boolean b, boolean c) {
    if (!a && b && !c) {
    }
}

public void bc(boolean a, boolean b, boolean c) {
    if (!a && b && c) {
    }
}

public void c(boolean a, boolean b, boolean c) {
    if (!a && !b && c) {
    }
}

public void none(boolean a, boolean b, boolean c) {
    if (!a && !b && !c) {
    }
}

Then just call all of them:

a(a, b, c);
ab(a, b, c);
abc(a, b, c);
ac(a, b, c);
b(a, b, c);
bc(a, b, c);
c(a, b, c);
none(a, b, c);
0
source

All Articles