Is there any appreciable difference between if and if-else?

前端 未结 9 947
执笔经年
执笔经年 2021-01-12 06:55

Given the following code snippets, is there any appreciable difference?

public boolean foo(int input) {
   if(input > 10) {
       doStuff();
       retur         


        
9条回答
  •  無奈伤痛
    2021-01-12 07:38

    Version #1 and #2 may be faster than #3, but I suppose the performance difference is minimal. I would rather focus on readability.

    Personally, I would never use version #2. Between #1 and #3, I would choose the one that yields the most readable code for the case in question. I don't like many exit points in my methods, because it makes the code hard to analyze. However, there are cases where the flow becomes clearer when we exit immediately for some special cases, and continue with the main cases.

提交回复
热议问题