Problem Solving Fundamentals · Approaching a Problem

Pin the input and output

the input–output contract

Pin the input and output

Picture a vending machine. You feed it coins and press a code, and a snack drops out. You never need to know what happens inside — the deal is what goes in and what comes out.

Code works the same way. Before you write a function, name what it takes in and what it gives back. Everything in between can stay vague for now.

Take this task: clean up a list of names. It is hard to start because the ends are missing. Does it take one name or many? Does it return a list, or one joined string? Pin those down and the task shrinks:

Input: an array of strings, some with stray spaces. Output: a new array of trimmed strings, in the same order.

Now the shape is concrete. Picture the array going in and a cleaner array coming out, one element for one element. The rule — trim each string — sits between them.

Notice what the contract decided for you. "A new array" means the input must not change. "Same order" means you are not sorting. A clear contract answers the questions you would otherwise discover halfway through, one bug at a time.

Pin the input first: what type, and how many? Then pin the output: the same shape, or something new? Write both down before you write the function body. When the two ends are fixed, the middle is the only part left to solve.

You are about to answer a short quiz on pinning the input and output.

  1. Naming a function's input and output makes the task easier to start.
  2. A function's input–output ___ states exactly what it accepts and returns.
  3. A function that returns a new array is allowed to change the array it was given.
  4. For a task that returns 'a new array, in the same order', the original array must stay ___.
  5. Pinning the input and output tells you the type and the number of values to expect.