Reduce the number of paths through a method
One of the best things you can do to keep code understandable is to limit the number, and length of, paths through a method. The simplicity of a method is not defined by a small number of inputs and outputs (e.g. Gosling style), but by the amount of mental bookkeeping needed in order to follow along with the code.
There are a couple of strategies for doing this: you can return early whenever possible, and relatedly, you can structure your conditionals to allow you to do that.
Always return early
At every step of the way you want to eliminate possible states that
the reader might have to keep track of, and this is the #1 way to do
that. Avoid storing return values in, for example, a ret
variable.
Instead, when you know what you’re going to return, return right
there and then, and you’ve saved the reader some work. If you don’t, the
reader has to follow the rest of the control flow to the end just to
verify that nothing else clobbers the ret
value!
Invert conditionals and bail
Here’s an easy way to do this. Wherever you’ve got this:
if (condition) { // Do many things } else { return null; }
Change it to this:
if (!condition) {
return null;
}
// Do many things
This will have the effect of flattening out your code, saving the reader from having to track many levels of nesting. You’re getting simple cases out of the way, and your code can proceed to the interesting work in confidence.