Return from the method immediately to any of these situations:
- You have found a boundary condition and you need to return a unique or control value:
if (node.next = null) return NO_VALUE_FOUND; - The required value / state is false, so the rest of the method is not applied (aka security point). For example:
if (listeners == null) return null; - The purpose of the method is to find and return a specific value, for example:
if (nodes[i].value == searchValue) return i; - You are in a section that returns a unique value from a method that is not used elsewhere in the method:
if (userNameFromDb.equals(SUPER_USER)) return getSuperUserAccount();
Otherwise, it is useful to have only one return statement, so that it is easier to add a debug log, clear resources, and follow logic. First I try to handle all of the above 4 cases, if applicable, and then declare a variable called result(s) as late as possible and assign values as needed.
source share