2012-07-12 50 views
0

如果我的代碼是一個簡單的塊:是否應該保留不必要的elses?

public void tracePath(){ 
    int steps = 0; 
    steps = bfs();  
    if(steps==0){ 
     pathFound(false); 
     System.exit(0); 
    }else{ 
     System.out.println(steps); 
     pathFound(true); 
     System.exit(0); 
    } 
} 

據我所知,這可能不其他被rewriten爲

public void tracePath(){ 
    int steps = 0; 
    steps = bfs();  
    if(steps==0){ 
     pathFound(false); 
     System.exit(0); 
    } 
    System.out.println(steps); 
    pathFound(true); 
    System.exit(0); 
} 

是否有性能(或其他邏輯)之所以這麼保持(或失去)其他?還是僅僅(在這個例子中)文體選擇?

+1

爲什麼甚至懶得設置: pathFound(假) 步驟== 0 因爲你要退出的時候?這看起來像一個巨大的代碼氣味。 – 2012-07-12 04:04:09

+0

這只是我在調試某些問題時使用的一些代碼。 退出只是在那裏,因爲我不是有興趣執行部分那時指出/ – TrewTzu 2012-07-12 06:07:11

+0

當出口不存在時,你的兩個例子是不相同的 – 2012-07-12 15:32:49

回答

1

在這種情況下,它是風格偏好,因爲您在if語句的末尾退出。如果在if的末尾沒有system.exit(0),則在第二個示例中,您將執行這兩個代碼段。

0

我要改變它咯,這樣:

public void tracePath(){ 
    int steps = 0; 
    steps = bfs();  
    if(steps==0){ 
     pathFound(false); 
    }else{ 
     System.out.println(steps); 
     pathFound(true); 
    } 
    System.exit(0); 
} 

雖然,說實話,調用System.exit從一個叫tracePath功能似乎在首位有點極端。

1

我會把它改成這樣:

public void tracePath(){ 
int steps = 0; 
steps = bfs();  
pathFound((!(steps==0))); 

System.exit(0); 
} 
相關問題