範例

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$
}

}