Design Strategies

From Design Patterns in Dynamic Languages by Peter Norvig. Design Strategies are what guide you to certain patterns, and certain implementations. They are more like proverbs than like templates. (Definition by comparing to Design Patterns.)

English Translation

To insure that your program says what you mean:

  1. Start with English description
  2. Write code from description
  3. Translate code back to English; compare to 1.

Example of code that doesn't follow this, from a Lisp textbook:

  1. “Given a list of monsters, determine the number that are swarms.”
  2. (defun count-swarms (monsters)
      (apply '+ (mapcar
                 #'(lambda (monster)
                     (if (eql (type-of monster)
                              'swarm)
                         1 0))
                 monsters)))
  3. “Given a list of monsters, produce a 1 for a monster whose type is swarm, and a 0 for others. Then add up the numbers.”

Example of code that follows the strategy. Note how clearer it is:

  1. “Given a list of monsters, determine the number that are swarms.”
  2. (defun count-swarms (monsters)
      (count 'swarm monsters :key #'type-of))
  3. “Given a list of monsters, count the number whose type is swarm.”