Learn the right way to write a program the wrong way

In my last post I reviewed a paper by David Parnas. In it he talks about the right way and the wrong way to decompose a program.

I’d like to show off how I like to do things, which is the wrong way. It’s a good skill to have, but one that a lot of beginners on Stack Overflow don’t know.

Here’s the four step method to doing things the wrong way

  1. Write a small story
  2. Turn each sentence into a comment
  3. Turn each comment into a subroutine
  4. Build out each subroutine

Step 1 - Write a small story

From the KWIC system from the last post, the story looks like this.

First we read the file. Then we shift every line. All the lines are alphabetized. Then we output the lines.

Step 2 - Turn each sentence into a comment

# First we read the file.
# Then we shift every line
# All the lines are alphabetized.
# Then we output the lines.

Step 3: Turn each comment into a subroutine call

Use the comments to produce some well-named subroutines with well-named variables

lines = read_file()
shifted_lines = shift_all_lines(lines)
alphabetized_lines = alphabetize(shifted_lines)
output(alphabetized_lines)

Step 4: Write the subroutines

def read_file():
  ...
  return lines

def shift_all_lines(lines):
  ...
  return shifted_lines

def alphabetize(shifted_lines):
  ...
  return alphabetized_lines

def output(alphabetized_lines):
  ...

lines = read_file()
shifted_lines = shift_all_lines(lines)
alphabetized_lines = alphabetize(shifted_lines)
output(alphabetized_lines)

And boom! Fill in the dot dot dots, and you have a wonderfully wrongly developed piece of software.