I often run into code that has to perform lots of checks and ends up being indented at least five or six levels before really doing anything. I am wondering what alternatives exist.
Below I’ve posted an example of what I’m talking about (which isn’t actual production code, just something I came up with off the top of my head).
public String myFunc(SomeClass input) { Object output = null; if(input != null) { SomeClass2 obj2 = input.getSomeClass2(); if(obj2 != null) { SomeClass3 obj3 = obj2.getSomeClass3(); if(obj3 != null && !BAD_OBJECT.equals(obj3.getSomeProperty())) { SomeClass4 = obj3.getSomeClass4(); if(obj4 != null) { int myVal = obj4.getSomeValue(); if(BAD_VALUE != myVal) { String message = this.getMessage(myVal); if(MIN_VALUE <= message.length() && message.length() <= MAX_VALUE) { //now actually do stuff! message = result_of_stuff_actually_done; } } } } } } return output; }
See Flattening Arrow Code for help.