Design by contract

Design by contract (DBC) is an approach to designing software that requires the definition of formal and verifiable specifications for software components. These specifications, referred to as contracts, can be:

  • side effects
  • preconditions
  • postconditions
  • invariants

Some engineers maintain that, for performance optimization, assertions should not be run in production software.

JavaScript assertion example

// Assertion helper function
function assert(condition, message) {
  if(!condition) {
    throw new Error(message);
  }
}
// Precondition
function increment(n) {
  assert(typeof n === 'number', 'expected n to be a number');

  return n += 1;
}