Six Rules For Writing Clean Code
Six Rules For Writing Clean Code
Rule # 2: Assign intuitive names to variables and functions You should use names to indicate f unctionality. T he name filter_coeff, f or instance, would be appropriate f or a variable that is a f ilter coef f icient. In the commenting example above, the name x reveals little about what that variable does. Rule # 3: Make ample use of white space To a C compiler, white space simply delimits tokens. Accordingly, extra spaces and newlines in your application may seem to be of small importance. In C and many other high-level languages, though, white space can help other developers to more easily understand your code. Although the two loops shown below are identical f rom the perspective of a compiler, the f unctionality of the second loop is clearer to human readers of the code. (Importantly, the Tab key was not used to indent the second loop. Since the Tab character does not expand identically on all machines, it should be avoided.) Rule # 4: Don't make your code
Rule # 4: Don't make your code unnecessarily complex A single line of C code can have multiple side ef f ects. Typically, though, a lengthy line of code that updates multiple variables is more dif f icult to understand than multiple, simple lines of code that accomplish this same objective. T hus, you should try to limit the number of actions perf ormed by each line of your code. You should likewise strive f or simplif ication when declaring f unctions; excessively lengthy routines should be broken into multiple parts. For the compiler, multiple statements on one line or single statement on multiple lines will produce the same code density. As it is easier f or the reader to have one statement per line, this is the recommendation, which has no impact on code ef f iciency. Rule # 5: Be explicit So that other developers will be able to quickly discern what each line of your code does, you should eschew syntax that obscures meaning. For example, in comparison statements that involve zero, you should avoid the syntax shown in the f irst of the below if statements. if (!tx_val) { err_cnt++; } Instead, your code should resemble the second if statement below. T his statement clearly indicates that the variable tx_val is being compared to zero. if (tx_val == 0) { err_cnt++; } Rule # 6. Apply rules uniformly Simply put, clean code is consistent code. To make sure that your style is consistent, you should use a coding standard, a f ormal document that elaborates on the type of rules that this article summarizes. For an example coding standard, you can visit the Web site of embedded sof tware provider Micrim. T here, you can download the standard that guides the ef f orts of each of Micrim's sof tware developers. T his coding standard is available f ree of charge.