Search code examples
oopdomain-driven-designdesign-by-contractdefensive-programmingpreconditions

Checking preconditions on parameters in public methods


I'm going to ask your Point of view about a design matter.

The question is basically the following: a public method of an object should always check preconditions in its input parameters or is it better to love responsibility to the caller and "trust the flow" ?

I'm not talking about obvious preconditions such as checking for null to avoid null reference exceptions, but I'm referring to business preconditions in method parameters. This typical happens in DDD Services that perform some kind of validation on input parameters and return an object containing a feedback about that validation.

As an example consider a class CheckPerson having a public method PerformCheck with a single parameter of type Person. Imagine there is a business rule saying that this check doesn't make sense for blonde persons.

In my opinion this check is important and method name should reflect this rule (something like PerformCheckForNonBlondePerson).

Should I add these checks, or should I trust the caller?


Solution

  • Yes you should!

    You need to differentiate between input validation and preconditions. Business rules, as you describe them, can be applied in both.

    Input validation happens at the system boundary. You expect input validation to fail in some cases. When that happens, you should indicate the error to the client with a useful description of the error.

    Preconditions, on the other hand, are part of the contract of a method (or a whole component) somewhere within your system. You always want to be sure this contract is adhered to, because your implementation will probably behave incorrectly otherwise. Here, we use guards to enforce the preconditions. A guard should always pass. If it does not, it is always a programmer error (as opposed to a user error).