Which code is better? Use return () in each condition:

void someProc(String str) { if (str.length < 1) { log("bad length"); return(); } if (str.charAt(3) == "N") { log("N at 3"); return(); } parse(str); } 

or nested conditions without return ():

 void someProc(String str) { if (str.length < 1) log("bad length"); else if (str.charAt(3) == "N") log("N at 3"); else parse(str); } 

What is best for performance?

Closed due to the fact that it is necessary to reformulate the question so that it was possible to give an objectively correct answer by the participants of Suvitruf ♦ , aleksandr barakin , Abyx , LEQADA , VenZell 28 December '15 at 12:59 .

The question gives rise to endless debates and discussions based not on knowledge, but on opinions. To get an answer, rephrase your question so that it can be given an unambiguously correct answer, or delete the question altogether. If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    But Dijkstra would not approve the first option, of course) - Nofate ♦
  • I would first of all think about whether these codes are any better? :-) Better for understanding, perhaps something like this: boolean checkConstrains (String str) {if (str.length <1) log ("bad length"); if (str.charAt (3) == "N") log ("N at 3"); return! ((str.length <1) && (str.charAt (3) == "N"))} void someProc (String str) {if (checkConstrains (str)) parse (str); } And manipulating the optimization options will be easier. - Chad
  • 2
    very interesting logic: return! ((str.length <1) && (str.charAt (3) == "N")) if the length is less than one , let's check the third symbol, and if the length is greater, then we will not =) - Specter
  • Ay, ah! get out! it is necessary || instead of && - Chad
  • one
    provided that the log function returns false , you could write a simple and concise code: boolean checkConstrains (String str) {return (str.length> 0 || log ("bad length")) && (str.charAt (3)! = "N" || log ("N at 3")); } - Specter

8 answers 8

If my memory serves me at the time of C (when java wasn’t there at all, or it was still not widely used), there was a rule / pattern that said that there could be only one exit point from the method.

Therefore, all methods had something like this:

 public boolean updateList(Object a, List<Object> list) { boolean updated = false; if (null !=list) { if (null != a && (a instanceof SomeObject)) { list.add(a); updated = true; } } return updated; } 

Perhaps it was the extreme, which resorted to after ate de..ma with goto operators. After all, the return behavior in void methods is similar to using the goto operator.

With the popularization of java, the ratio of people who read the code to those who write it increases. Therefore, it is now more important to write more readable code. Therefore, I believe that this type is more acceptable:

 public boolean updateList(Object a, List<Object> list) { // can't do much more if (null == list) { return false; } // nothing to add to the list // object is null or has invalid type if (null == a || !(a instanceof SomeObject)) { return false; } // update list, return result list.add(a); return true; } 

I always write code in a similar style because:

  1. it is convenient for me to read;
  2. colleagues have never complained;
  3. comments break the code into easy-to-read, logically related groups (try adding comments to the previous example, they will be lost in the code, especially if the formatting with an opening bracket is in the same line);
  4. easy to track the logic of the method;
  5. if you are writing documentation, and specifically unit test plan, then a similar structure of the code suggests which test cases should be added (well, order).

It is worth adding that any program / method first checks the arguments, and then works with them. And not always checking the arguments is part of the program / method logic, it makes sense to separate them.

    It's not about performance, but about logic. Options differ in semantic load.

    When you write:

     if (a) { } elseif (b) { } else { } 

    this is equivalent to the following:

     if (a) { } else { if (b) { } else } 

    Those. verification of the second condition (and the execution of the corresponding block) is possible only if the first condition is false. In this case, of course, you can say about the performance gain for some share in a long cycle.

      Option 1 is different in every way better, and in all respects. To me on the drum this your Dijkstra - BTW: WTF?

      1. More economical in terms of inspections
      2. Sleeker
      3. More transparent

      The only thing that can only be improved is the one proposed by @ Chad , provided that checkConstrains() is called somewhere else.

        Second. The code is more readable. else if these are not nested conditions. It is better to avoid multiple return in the middle of a method, especially a void method. About any grace in the 1st version of the speech does not go. I don’t know what tasks you have, but if your code is read by others, think first of all about making everything beautiful. Java is still not the most sharpened tool for resource saving, other goals. As for performance, I don’t see any differences, can anyone explain?

          There is a remarkable rule: return the result as soon as you get it. It allows you to avoid nested loops, makes the code easier and clearer.

          • one
            And there is a rule that the output from the function should also be one. I would strongly argue that the set of returns makes the code simpler and clearer. Everything is good in moderation. Your rule can and will avoid nested loops, but adds crap with resource release. Yes, and branching to understand it will be harder. - Chad
          • 2
            The desire to make one return often generates monstrous constructions that are difficult to read. - Snow
          • Moderately all is well! In moderation !!! A large number of return s are also hard to read. ** CORRECT ** the result of the function is better to return in one place, and not through one place :-) - Chad

          Performance needs to be measured AFTER the code is written. Do not prematurely optimize. This applies to ANY programming language.

          Understand that Intel processors may be good for performance, for AMD it will be like death. Only profiler, only equipment on which the system will work. In Java cases, the same JVM version is also. If this method is not a hot spot / point, you should not engage in such a petty optimization - your code will be read more, concentrate on that. In this particular case, one return is better.

          Another moment. Do not use the procedural style in Java. User jmu gave you a good code sample.

          • one
            Only here the @jmu sample (IMHO good code) has several returns and is unconditionally written in a procedural style (which, by the way, is easier to read by most programmers). - avp
          • What about the procedural style does not quite agree. For me, the procedural code in OOP is 15 private methods that are called from each other, not accepting values ​​and returning nothing. It is impossible to test, it is tiresome to refactor. So the @jmu option for me looks like OOP :) The first listing with one return is Anton Feoktistov

          As for performance, it does not depend on the code itself, but on how it is assembled and executed, that is, it needs to be tested, and there may be a different result on different Java machines, like on different hardware. The idea behind return is heavier, since there is an implicit function call, variable assignments, etc.

          As for writing, the boundary conditions are usually checked (by which an exit can be made), and the rest often fits into the switch construction.

            I myself write in the first style (in different languages) and so far there are no problems with anything.

            • I basically too. Checking return (s) or goto, then the algorithm itself. - avp pm