Write Code Like You Write a Recipe


As it tends to do, time continues to move on. The project and code in it eventually becomes legacy code (aka, someone else's problem to maintain).

One day, the business drudges up that old automated cookie creation idea and requests that it handles a new task - "instead of just cooking peanut butter cookies, it'd be great if the cookie system could handle oatmeal raisin as well!".

Hah! You remember that old system, but you're onto newer and better things. This is a perfect task for the intern to sink their teeth into - afterall, it's legacy and not high profile, it's been stable, and it was so simple to implement the first time around.

The new set of requirements/recipe the intern works off of looks very similar to the initial ones:

  • Step 1: Preheat oven to 325F, grease cookie sheet
  • Step 2: In bowl, stir oats, pumpkin puree and sugar until smooth.
  • Step 3: Beat in one egg white, then stir in baking soda, salt, and cinnamon.
  • Step 4: Roll dough into 1 inch balls and place 2 inches apart on the sheet.
  • Step 5: Bake for 8 minutes, cool for 5, enjoy!

He eagerly begins to expand the original code to handle the new case:

function makeCookies (type = 'peanut-butter') { if (type === 'peanut-butter') { oven.setTemperature(350) } if (type === 'oatmeal-raisin') { oven.setTemperature(325) } sheet.grease() if (type === 'peanut-butter') { bowl.add(peanutButter) bowl.add(sugar) } if (type === 'oatmeal-raisin') { bowl.add(oats) bowl.add(pumpkinPuree) bowl.add(sugar) } bowl.stir() if (type === 'peanut-butter') { bowl.beat(egg) bowl.beat(egg) bowl.stirIn([bakingSoda, salt, vanilla]) } if (type === 'oatmeal-raisin') { bowl.beat(eggWhite) bowl.stirIn([bakingSoda, salt, cinnamon]) } const dough = bowl.makeDough() sheet.add(dough.balls()) oven.add(sheet) if (type === 'peanut-butter') { oven.setTimer(10) } if (type === 'oatmeal-raisin') { oven.setTimer(8) } const cookies = oven.remove(sheet) sheet.cool(10) return cookies
}

The code comes in, the peer reviews pass it as it meets the requirements and nothing is obviously wrong. Still, it has become a bit harder to understand and you're left with a nagging feeling.