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?


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).


@theDmi thanks for sharing your point of view.
I totally agree with your position.

The context when I'm currently working is a team of three people, implementing a large application with a good deal of business logic and domain rules to be taken into account.
The main reason I don't agree with the "trust the flow and delegate responsibility to the caller" philosophy is that this force every developer which is going to make a call to a domain service to explicitly read the code of such a service and to have a good knowledge about the business requirement behind that code.
In my opinion, this is not realistic and furthermore this is an error-prone process.

Domain layer in large application is called by every piece of application logic we are going to write and leaving all the responsibility to the caller is simply too dangerous in my opinion. We don't currently use any kind of library to enforce preconditions check, but I know there are several options out there :)

链接地址: http://www.djcxy.com/p/76234.html

上一篇: XMLEventReader / XMLStreamReader是否引发IllegalArgumentException

下一篇: 在公共方法中检查参数的先决条件