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:
- it is convenient for me to read;
- colleagues have never complained;
- 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);
- easy to track the logic of the method;
- 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.
log
function returnsfalse
, 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