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 alternativ
You can get rid of some of the nesting by using guard clauses.
public String myFunc(SomeClass input)
{
Object output = null;
if(input == null) return "";
SomeClass2 obj2 = input.getSomeClass2();
if(obj2 == null) return "";
SomeClass3 obj3 = obj2.getSomeClass3();
if(obj3 == null || BAD_OBJECT.equals(obj3.getSomeProperty()))
{
return "";
}
SomeClass4 = obj3.getSomeClass4();
if(obj4 == null) return "";
int myVal = obj4.getSomeValue();
if(BAD_VALUE == myVal) return "";
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;
}
Change all of the return ""; statements that I used to illustrate the point to statements that throw a descriptive variety of Exception, though.