範例

public static void main( String[] args ) {
if ( args.length > 3 ) {
System.out.println( "More than 3" ); //$NON-NLS-1$
if ( args[ 0 ].startsWith( "a" ) ) { //$NON-NLS-1$
System.out.println( "Starts with a" ); //$NON-NLS-1$
if ( args[ 1 ].endsWith( "z" ) ) { //$NON-NLS-1$
System.out.println( "Ends with z"); //$NON-NLS-1$
}
}
}
}

解決方案
反轉條件並加入 return 陳述式。
以下解決方案說明於重構中(由 Martin Fowler 說明)。
  1. 反轉最外層 if 陳述式的條件。
  2. if 陳述式下方加入 return 陳述式。
  3. 重複這些步驟,直到不再有更深的巢狀 if 陳述式為止。

public static void main( String[] args ) {
if ( args.length <= 3 ) {
return ;
}

System.out.println( "More than 3" ); //$NON-NLS-1$

if ( !args[ 0 ].startsWith( "a" ) ) { //$NON-NLS-1$
return ;
}

System.out.println( "Starts with a" ); //$NON-NLS-1$

if ( args[ 1 ].endsWith( "z" ) ) { //$NON-NLS-1$
System.out.println( "Ends with z"); //$NON-NLS-1$
}

}