How to Design Functions - mottosso/SPD1x GitHub Wiki

The course provides a design guide, called "HtDF", for designing functions that goes something like this.

  1. Signature, purpose and stub.
  2. Define examples, wrap each in check-expect.
  3. Template and inventory.
  4. Code the function body.
  5. Test and debug until correct

Applied in Python

This is a prime example of test-driven design, in which you write tests before you implement the functionality.

1. Signature, purpose and stub

The signature

def mult(a, b):
  """Multiply two numbers
  
  Arguments:
    a (float): First operand
    b (float): Second operand

  Returns:
    (float) product of `a` and `b`

  """

  return 0

2. Define examples, wrap each in check-expect.

What they call "examples wrapped in check-expect" is what we call "tests".

assert mult(1, 2) == 2
assert mult(2, 4.2) == (2 * 4.2)

3. Template and inventory.

A template, or "mock", is a general outline of how you expect to start implementing a function. Think of it like a sketch.

def mult(a, b):
  ...
  return product

4. Code body

def mult(a, b):
  return a * b

5. Test and debug until correct

Should the above body not entirely pass those tests, then this is where you'd go back and make sure it does.