Comparison
Guard clausevsNull object
Guard clause
the invalid cases return in the first four lines, and the rest of the method is not indented at all.
Handling exceptional or invalid input with an immediate return at the top of a method, so the main path is unnested. It is the standard cure for deeply nested conditionals and makes the preconditions readable as a list. It is the smallest structural change in this corpus and the one most likely to be worth making in code you are reading right now.
Full entry →Null object
instead of returning null you returned something that implements the interface and does nothing, and the null checks disappeared.
Supplying a valid object with neutral behaviour in place of a null reference, so callers do not have to branch. It works beautifully for collaborators with no meaningful absence — a no-op logger, an empty collection, a permissive policy — and badly where absence really is a case the caller must handle, because it turns a loud failure into a silent nothing. That is the line between it and an option type, which makes absence explicit rather than invisible.
Full entry →