Design ideas needed for bunch of conditional if-else

Viewed 45

I have a simple logic to implement. But not sure if there is a better way to design it, other than simple if-else or switch statements.

There are 4 permissions (consider them boolean variable), which can be true or false. Based on various conditions (permutations of those permissions), i need to return list of String values that need to be displayed on UI for a dropdown field.

So its like this for now -

if(!permission1 && !permission2){return list_of_strings_1;}
else if (permission1 && permission2 && !permission3){return list_of_strings_2;}

and so on. Some of them are just if statements. So multiple conditions maybe true and we have to collect all the list of strings and display them.

Those if elses go on for quite some time (about 100 lines). Each will return different list of strings. Most of it is NOT likely to change in future. So maybe too deep of a design maybe an overkill.

But just wondering how experts would refactor this code (or if they will even refactor it or not). Maybe sticking to switch/if-else is ok?

1 Answers

I don't understand how four flags gives you 100 lines of code. This can be done with a map of 16 entries (or less, if some combinations are invalid and can be mapped to a default). If the string representation is truly a list of strings, one for each possible permission, the solution is even more compact.

The key is an object representing the combination of permissions, and the value is the string representation for that combination. You could create a custom type for the key, but in this example, I'm just using four bits of an integer, where each bit indicates whether the permission is granted or not:

private static final int P1 = 1 << 0, P2 = 1 << 1, P3 = 1 << 2, P4 = 1 << 3;

private static final Map<Integer, String> permissionsToString = Map.ofEntries(
  Map.entry( 0, "No permissions granted."),
  Map.entry( 1, "Permissions 2-3 revoked."),
  Map.entry( 2, "Permission 2 granted."),
  ...
  Map.entry(14, "Permission 1 revoked"),
  Map.entry(15, "Superuser"));

public static String toString(boolean p1, boolean p2, boolean p3, boolean p4) {
  int key =   (p1 ? 0 : 1) << 0
            | (p2 ? 0 : 1) << 1
            | (p3 ? 0 : 1) << 2
            | (p4 ? 0 : 1) << 3;
  return permissionsToString.get(key);
}

If you don't understand bits, you can use an EnumSet or define your own value object to represent the key at a higher level. The idea is the same: map all possible combinations (24 = 16) to their corresponding label.

Related