Rewriting Nested If/Else

An often overlooked (perhaps) way to write cleaner if condition statements. This is not about having to go through all the refactoring into a Factory pattern, Switch statements, and other possible conditional logic methods just to avoid our classic if condition. Rather merely making it look better, when the scenario is right for it. Of course. I mean if I really only need a simple if statement, I’ll just write it as one and don’t need to overcomplicate things.

Now, diving right in. There is a tendency to write this kind of if/else block of code (example shown below) as more rules are introduced over time. This commonly happens too when more than one is working on the code, and conditions are just inserted to accomplish the goal. I’ve been guilty of doing this for reasons such as I wanted to keep the older code closely resembling to how I found it.

1 public void beginProcessing() {
2           if (isAllowedType) {
3
4                if (!SpecialMember.NONE.equals(userId)) {
5
6                    if (foo != null) {
7                        Object bar = getSomething(foo);
8                         
9                        if (isUnique(bar)) {
10                          doSomething();
11                       } else {
12                          System.out.println("Not unique");   
13                       }
14                         
15                  } else {
16                     System.out.println("Foo is null");
17                  }
18
19               } else {
20                   System.out.println("User is not a member");
21               }
22
23          } else {
24               System.out.println("Type not allowed");
25          }
26 }

I can rewrite this into a more organized structure of if statements less the else.

1 public void beginProcessing() {
2           if (!isAllowedType) {
3              System.out.println("Type not allowed");
4              return;
5           }
6
7           if (SpecialMember.NONE.equals(userId)) {
8              System.out.println("User is not a member");
9              return;
10          }
11
12          if (foo == null) {
13             System.out.println("Foo is null.");
14             return;
15          }
16
17          Object bar = getSomething(foo);
18
19          if (!isUnique(bar)) {
20             System.out.println("Not unique");
21             return;  
22          }
23
24          doSomething();
25 }

Now it reads better, easier to understand. It is like going through a list of the rules of what shouldn’t be, before action is finally taken on something. This removes the unsightly else conditions. The desired output in this csae is still the same. The log messages are kept too.

At this point having to do it this way is still manageable. If there are too many conditions already, then maybe it is time to refactor the code into something else.

Also wrote about replacing nested if/else conditions by using Java 8 Stream here.

Similar Posts: