0

If i have a simple chunk of code like:

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);
   }
}

AFAIK this could be rewriten without the else as

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);
}

Is there a performance (or other logical) reason so keep (or lose) the else? or is it just (in this example) stylistic choice?

4

3 回答 3

1

在这种情况下,这是风格偏好,因为您在 if 语句的末尾退出。如果在 if 末尾没有 system.exit(0),则在第二个示例中,您将执行两段代码。

于 2012-07-12T03:52:24.273 回答
1

我会把它改成这样:

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

System.exit(0);
}
于 2012-07-12T06:44:50.280 回答
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看起来有点极端。

于 2012-07-12T03:54:17.217 回答