Weak or strong pre-conditions?

A very important design decision when modeling contracts is whether to use strong or weak contracts. This is a matter of trade-offs.

Consider a method with a weak pre-condition. For example, the method accepts any input value, including null. This method is easy for clients to use for the clients: any call to it will work, and the method will never throw an exception related to a pre-condition being violated (as there are no pre-conditions to be violated). However, this puts an extra burden on the method, as it has to handle any invalid inputs.

On the other hand, consider a strong contract: the method only accepts positive numbers and does not accept null values. The extra burden is now on the side of the client. The client must make sure it does not violate the pre-conditions of the method. This may require extra code.

There is no clear way to go, and the decision should be made considering the whole context. For example, many methods of the Apache Commons library have weak pre-conditions, making it much easier for clients to use the API. Library developers often prefer to design weaker pre-conditions and simplify the clients’ lives.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *