反转条件并添加 return 语句。
Martin Fowler 的 Refactoring 中探讨了下面的解决方案。
- 反转外围程度最深的 if 语句。
- 在 if 语句下面添加一个 return 语句。
- 重复上述步骤,直到不再有更多深度嵌套的 if 语句。
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" );
}
}
|
|