Six Rules for Writing Clean Code

As embedded systems developers, many of us are veterans of multipleprogramming courses. In college, we received instruction on a vastassortment of different algorithms and data structures.

Most of us were also taught the semantics of at least one high-levelprogramming language. There are surprisingly few engineers, though, whohave received significant instruction on the fundamental topic ofcoding style.

Programming courses teach what can and can't be done with aparticular language, but they often fail to demonstrate what should bedone in order to produce clear-cut, manageable code.

The exclusion of this topic from programming curricula does notindicate that coding style is inconsequential. To the contrary, thestyle in which a program is written affects how that code functions,and determines whether or not it can be easily supported.

Developers who have adopted an effective style produce software thatother programmers can readily understand and update. On the other hand,developers who lack such a style turn out code that causes innumerableheadaches for the engineers who are responsible for its maintenance.

What actually constitutes an effective coding style? Six generalrules for writing clean code are provided below. These guidelines willhelp you steer clear of the problems that poor coding style creates.

Rule #1. Use pithy comments
When other engineers attempt to discern how your code works, they'lllikely turn to your comments. Thus, you should make sure that thesecomments form an accurate description of the code. You should alsoavoid stating what would be obvious to another engineer. The first ofthe below C comments provides its reader with useful information, butthe second is frivolous. (Constants are hard-coded in the below codeand elsewhere in this article. You should normally use #defineconstants in place of such hard-coded values. )

while (usb_pkt_rdy == 0) {   /* Wait until atleast one packet has been received */

x =0;                                    /* Set x to0                                                                  */

Rule #2: Assign intuitive names to variables and functions
You should use names to indicate functionality. The name filter_coeff , for instance,would be appropriate for a variable that is a filter coefficient. Inthe commenting example above, the name x reveals little about what thatvariable does.

Rule #3: Make ample use of white space
To a C compiler, white space simply delimits tokens. Accordingly, extraspaces and newlines in your application may seem to be of smallimportance.

In C and many other high-level languages, though, white space canhelp other developers to more easily understand your code. Although thetwo loops shown below are identical from the perspective of acompiler, the functionality of the second loop is clearer to humanreaders of the code. (Importantly, the Tab key was not used toindent the second loop. Since the Tab character does not expandidentically on all machines, it should be avoided. )

Rule #4: Don't make your code unnecessarily complex
A singleline of C code can have multiple side effects. Typically, though, alengthy line of code that updates multiple variables is more difficultto understand than multiple, simple lines of code that accomplish thissame objective.

Thus, you should try to limit the number of actions performed byeach line of your code. You should likewise strive for simplificationwhen declaring functions; excessively lengthy routines should be brokeninto multiple parts.

For the compiler, multiple statements on one line or singlestatement on multiple lines will produce the same code density. As itis easier for the reader to have one statement per line, this is therecommendation, which has no impact on code efficiency.

Rule #5: Be explicit
So that other developers will be ableto quickly discern what each line of your code does, you should eschewsyntax that obscures meaning. For example, in comparison statementsthat involve zero, you should avoid the syntax shown in the first ofthe below if statements.

        if (!tx_val) {
            err_cnt++;
        }

Instead, your code should resemble the second if statement below.This statement clearly indicates that the variable tx_val is beingcompared to zero.

        if (tx_val == 0) {
            err_cnt++;
        }

Rule #6. Apply rules uniformly
Simply put, clean code isconsistent code. To make sure that your style is consistent, you shoulduse a coding standard, a formal document that elaborates on the type ofrules that this article summarizes.

For an example coding standard, you can visit the Web site ofembedded software provider Micriµm. There, you can download thestandard that guides the efforts of each of Micriµm's softwaredevelopers. This coding standard is available free of charge.

Matt Gordon , Technical Marketing Engineer, at www.micrium.com has severalyears of experience as an embedded software engineer, and isresponsible for explaining the nuances of this the company's softwareto Micriµm's partners and customers. Matt holds a bachelor'sdegree in computer engineering from Georgia Tech.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.