Wednesday, 1 January 2014

Guideline #1. Do one thing at a time

Guideline

  • Put each instruction in one separate line of code.
  • Each instruction shall do exactly one thing.

Discussion

This will enhance the readability of your code and make it easier to debug and possibly change in the future.

It should not be possible for an instruction to have several causes of failure. Constructing objects, calling functions and combining several values into a nontrivial expression are operations relevant enough to deserve their own line of code.

For example, if an instruction is a function call, its arguments should be trivial expressions. If they are not, their values should be obtained in independent instructions prior to the function call. If the purpose of that function call is to get some result, don’t do anything complicated with it once you get it. Instead, place the result in a variable and do subsequent operations with it in the following lines.

If you write code in this way you will find out that it follows your train of thought quite closely. For this reason, a future reader (whether it is another programmer or you) will have a better chance of understanding it.

Example

Don't

int i = 0, j = 1;

(…)

i = ++j;

In the don't section you see that two variables are declared in the same line. After doing some omitted work which possibly changes their initial values, j is incremented, and the result of this increment is assigned to i.

Do

int i = 0; // Count of i
int j = 1; // Count of j

(…)

++j;
i = j;


This code puts the two variable declarations in separate lines, thus complying with the guideline and allowing to easy document their meaning - something which may not always be necessary, but which should always be considered.

The change of value of j (its increment) is given a specific line of code, and after that, the assignment of the value of j to i is performed. The code becomes instantly clearer, just by doing one thing at a time.

Bibliography

This materials referenced in this section discuss the issue described above in more detail.

  • Steve McConnell: Code Complete, 2nd Edition, Microsoft Press, Redmond (Washington, USA), 2004.
This book discusses layout in Chapter 31: "Layout and Style". In particular, see Section 31.5 "Laying out individual statements" and its Subsection "Using Only One Statement Per Line" (page 758-761).

No comments:

Post a Comment