Image by Steve Buissinne from Pixabay

The defensive programming principles state that we should validate and assert the preconditions (input parameters, return values of called methods, current system state) before executing the particular method code. The obvious benefit of this approach is it allows you to catch bugs early and to get a reasonable stacktrace that limits the scope for finding the error in the code.

As a simple example, if we explicitly check an input parameter for nullability and throw at the beginning of the method, then in case of an error the investigator would know for sure that the bug is somewhere in the calling code, not in the method itself. If however we don’t validate, and the exception occurs later somewhere inside the body of our method, or worse, down the calling stack, the investigator would spend some time until she figures out that the problem is not actually in the method where the exception was thrown, but somewhere up the stack.

In a more complex case, suppose the process consists of multiple backend invocations. We then encounter an error during the last invocation. But what if the condition that caused this error actually appeared during one of the previous invocations? In this case, we wouldn’t have any relevant stacktrace for this error at all. Defensive programming could help us catch errors closer to where they happen and reduce the time for investigation.

How much should we check? From the point of view of the code stability, the more checks we have, the better. But we should keep the set of validations discreet, so as not to fill each and every method with dozens of lines of duplicating validations that never catch anything and just create visual noise.

We should instead establish a “trust border” between different sets of classes and methods. There’s no strict set of rules on where to set a “trust border”, but here are some guidelines:

  • code in a particular class most likely should trust the code in the same class (e.g. there’s no need for heavy validation when calling one method of a class from another);
  • if a set of classes represent a cohesive functionality, then those classes should trust each other. An example could be a set of services and helper classes that implement a particular algorithm — they are most likely developed and tested together, and the preconditions should be validated at the beginning of the algorithm;
  • one layer most likely shouldn’t trust another layer; e.g., when you call the REST layer from the frontend, you should definitely validate inputs; likewise, when you call service layer from the REST layer;
  • common and utility classes and services should never trust the caller to provide correct input values;
  • one microservice definitely shouldn’t trust an input from another microservice; one buggy microservice shouldn’t drag along the whole system.