Repurpose Code Contracts in Production Code RRS feed

  • Question

  • Hi,

    I just wanted to know your opinion if it is a good idea to use Code Contracts for input validation and return value checks in production code. There are plans to get good Api documentation for all thrown exceptions and boundaray conditions by simply removing the input checks in favor of Code Contracts so we get automatic exception documentation.

    As far as I have understood Code Contracts its original intent was to add these Contracts as additional safeguards in internal methods of e.g. an algorithm. When you remove the contracts it is expected that the code will continue to work. This would not be the case if we simply remove the input checks here. Since the ContractException is internal there is no way to catch it by its type anymore which could cause adverse effects in our code base. I know that you can replace the ContractException somehow but this is not the norm. Do you have an example for a specific Contract which throws a different Exception?

    Tuesday, April 15, 2014 9:37 AM

All replies

  • No.

    Input validation should happen , as far as possible, before the values get anywhere near the code that is guarded with a contract.

    Also input validation can be stricter than the contracts on the code.  For instance you might have a library of functions that perform some complex mathematical functions.  The contracts will delineate the range of input values that will not cause the algorithms to fail.  However it can be that you have business rules that constrain the users to a much smaller range of values in order to catch typos when you know that certain values are out of range for your application.

    These checks should be made without throwing exceptions of any kind because they are part of the normal flow of control in the application.  In general input validation does not need to throw exceptions, validation failure is not an exceptional event and exceptions should not be used as a control flow mechanism.

    Thursday, May 15, 2014 8:46 AM