Thursday, March 22, 2012

The Art of Readable Code – Extracts

Source: The Art of Readable Code–Extracts

Basic Rules:

  • Code should be easy to understand.
  • Code should be written to minimize the time it would take for someone else to understand it.

Surface-Level Improvements

  • Picking good names,
  • Writing good comments,
  • Formatting your code neatly

About names

The best names are ones that can’t be misconstrued—the person reading your code will understand it the way you meant it, and no other way. Unfortunately, a lot of English words are ambiguous when it comes to programming, such as filter, length, and limit.
Before you decide on a name, play devil’s advocate and imagine how your name might be misunderstood. The best names are resistant to misinterpretation.

  • Packing Information into Names
  • Choosing specific words
  • Avoiding generic names (or knowing when to use them)
  • Using concrete names instead of abstract names
  • Attaching extra information to a name, by using a suffix or prefix
  • Deciding how long a name should be
  • Using name formatting to pack extra information

Naming Booleans

When picking a name for a boolean variable or a function that returns a boolean, be sure it’s clear what true and false really mean.

In general, adding words like is, has, can, or should can make booleans more clear.

It’s best to avoid negated terms in a name.

Lines of code

Instead of minimizing the number of lines, a better metric is to minimize the time needed for someone to understand it.

Variables

  1. The more variables there are, the harder it is to keep track of them all.
  2. The bigger a variable’s scope, the longer you have to keep track of it.
  3. The more often a variable changes, the harder it is to keep track of its current value.

Functions

  1. Look at a given function or block of code, and ask yourself, “What is the high-level goal of this code?”
  2. For each line of code, ask, “Is it working directly to that goal? Or is it solving an unrelated subproblem needed to meet it?”
  3. If enough lines are solving an unrelated subproblem, extract that code into a separate function.

One task at a time

Here’s the process we use to make code do “one task at a time”:

  1. List out all the “tasks” your code is doing. We use the word “task” very loosely—it could be as small as “make sure this object is valid” or as vague as “iterate through every node in the tree.”
  2. Try to separate those tasks as much as you can into different functions or at least different sections of code.

0 comments:

Post a Comment