Invert the condition and add a return statement.
The following solution is discussed in Refactoring by Martin Fowler.
- Invert the condition of the outer-most if statement.
- Add a return statement below the if statement.
- Repeat these steps until there are no more deeply nested if statements.
public static void main( String[] args ) {
if ( args.length <= 3 ) {
return ;
}
System.out.println( "More than 3" );
if ( !args[ 0 ].startsWith( "a" ) ) {
return ;
}
System.out.println( "Starts with a" );
if ( args[ 1 ].endsWith( "z" ) ) {
System.out.println( "Ends with z" );
}
}
|
|