3

I have seen many questions like this and this. Some people see there is overlapping between TDD and Design by Contract and others say they are complementary, I am biased to the second one, so I need a very basic, correct and complete example in any language or even in pseudo on how to use them together.

Drifter
  • 61
  • 4

1 Answers1

2

This is a slightly tricky question because both "test driven development" (TDD) and "design by contract" (DbC) imply something about your development process. (generally that the tests/contracts are written before the code)

Since you're asking about code examples, though, you are more interested in what it would look like to use tests and contracts together. Here is an example:

def sort_numbers(nums: List[int]) -> List[int]:
  '''

  Tests:
  >>> sort_numbers([4, 1, 2])
  [1, 2, 4]
  >>> sort_numbers([])
  []

  Contracts:
  post: len(__return__) == len(nums)
  post: __return__[0] <= __return__[-1]

  '''
  return sorted(nums)

Tests

We use tests to check how specific inputs affect the output. For example, sorting the numbers [4, 1, 2] produces the list [1, 2, 4]. Furthermore, sorting the empty list produces the empty list.

(these tests are written using doctest and can be checked with python -m doctest <file>)

Contracts

We use contracts to ensure that some properties hold, no matter what the inputs are. In this example, we assert that:

  1. The returned list has the same length as the input list.
  2. The first item returned is always less than or equal to the last item returned.

(these contracts are written in PEP-316 syntax and can be checked with CrossHair)

pschanely
  • 144
  • 1
  • 8