TruePERSPECTIVES_logo.png

Should your source code be as beautiful as a Shakespeare novel? [how to write readable and maintainable code]

Posted by Magnus Unemyr on Oct 17, 2016 2:19:30 PM

Software developers – like most other professionals – have their own areas where people have strong opinions on how something should be done. For embedded developers, one such area is the “look” of the source code. Few things are so personal to a software developer as the coding style he or she prefers.

You may be a Kernighan and Ritchie (K&R) guy, a Whitesmiths guy, or you are a “rebel” who create your own coding style. Or even worse, you are a coding cowboy who doesn’t follow any coding standard. Either way, a good editor is a critical tool to simplify your coding efforts. This blog post will teach you more on how developers can code in style and how great editors can make your life easier.

 

codeformatting.png

 

The art of writing good source code

Let’s start from the beginning. What is a coding style, and why would you like to use one?

Since the ancient times of early programming, writing code that is easy to understand has been important – in fact, it is one of the most critical tasks in making your code extensible and maintainable – along with adding descriptive comments and refactoring the code into a well-architected design with clear partitioning and few but well-designed interfaces.

So we might ask ourselves: What are coding standards, and how does it relate to code formatting?

Coding standards are rule-sets that define how you must write your code – the aim here is to follow best-practice, thus avoiding to introduce bugs or write code that is hard to understand and expensive to maintain.

With that interpretation, coding standards are formal rule sets that define what parts of a programming language (in our case, C or C++) you are allowed to use, or how you must or must not use them. Examples are MISRA-C, JSF or CERT-C. They are usually published by large organizations and support certification of safety critical systems. You will need special static code analysis tools to check whether or not your code complies to any of those coding standards.

Without following the rigor of coding standards intended for safety-critical use, any embedded developer can get great benefits from writing the code in a standardized way. In its simplest form, it can be formatting your code in a standardized way to make it easy to read, understand, and maintain.

The most common type of formatting standard enforcement almost every developer use is to indent code blocks. It is rare to see for- and while-loops, or if-then-else logic, that is not indented to improve clarity. Since code block indentation is so common, any programming editor worth its salt should do this automatically.

But now come a lot of related questions where developers have their own opinions, and often very strong ones at that. For example, should the curly brackets around the code block be indented as well, or not? How many characters should the indentation be? Should the code block’s opening curly bracket be at the end of the line above, or on its own line below? Should comments be to the right of the code, or on their own lines? Should comments be in C or C++ style? The list goes on.

Trivial decisions like these often turn into “religious wars”, as developers often feel so strongly about this. In my mind, it doesn’t matter so much which code formatting style you chose, as long as it improves readability, understandability, and maintainability – and as long as it is applied consistently across all files in a project. Pick any style you like and stick with it.

If you don’t want to invent your own code formatting standard, there are plenty to choose from. Atollic TrueSTUDIO, and Eclipse in general comes with a few popular and well-known code formatting standards:

Kernighan and Ritchie (K&R)

Brian Kernighan and Dennis Ritchie created the C programming language, for the purpose of writing the Unix operating system. The Kernighan and Ritchie coding standard (K&R) is the coding style they used in their popular book “The C programming language”.

Example:

kr.png

 

BSD/Allman

The Allman style is named by Eric Allman. He wrote many of the BSD Unix tools using this coding style.

Example:

bsd.png

 

GNU 

The GNU coding style was used by Richard Stallman, the father of the GNU tools.

Example:

gnu.png

 

Whitesmiths

The Whitesmiths coding style (sometimes called the Wishart style), was used in the documentation of the first commercial C compiler – the Whitesmiths compiler.

Example:

whitesmiths.png

 

There are many other well-known coding styles, for example, Horstmann, Pico, Ratliff, Lisp, Haskell, and more. Read this Wikipedia article for more details.

Tool support for code formatting

Any modern C/C++ code editor should include functions for code format selection and automatically adjust the editor behavior to simplify writing code in the selected style using “on-the-fly” code formatting as-you-type in the editor (real-time source code parsing and formatting).

Additionally, modern tools include editor productivity commands, like:

  • Auto-format the selected source code line(s)
  • Auto-format the entire file
  • Auto-format the code changes in the current editing session
  • Toggle code line(s) as line or block comment
  • Indent left or right, and auto-indent to the correct indent level
  • Sort selected lines in alphabetical order
  • Surround the selected line(s) with…if, while, function definition, etc.

Atollic TrueSTUDIO, for example, provides a lot of convenient editor functions in the “Source” menu:

 

sourceeditor.png

 

Adding tool support for your own coding styles

For the auto-formatting capabilities of your source code editor to work to your advantage, you need to be able to configure it to the coding style you standardize on. Your code editor should thus enable you to select from different common pre-defined formatting standards and allow you to create completely custom code formatting standards.

This screenshot shows how you can define custom formatting standards using Atollic TrueSTUDIO:

customstyle.png 

 

Naming conventions for symbols and other identities

In addition to code formatting, coding style also includes naming conventions for symbols like variables, data structures, functions, and even file names.

No matter how well-formatted and well-commented your source code is, the code may become very difficult to understand and maintain, if don’t use descriptive symbol names too.

There are many ways to craft symbol names; for example, by inserting characters that denote the data type of a variable, using lower-case or upper-case characters in different ways, or by separating words using underscore characters. Examples are Hungarian notation and Camel case.

In Hungarian notation, the data type is encoded in the variable name, for example, “pfSpeed” for a pointer to a float containing the speed value. The intention of Hungarian notation is to make error-prone type conversions more easy to spot and avoid.

With Camel case, multi-word symbols (without word separator characters) are written in lowercase, with each first letter of every new word in uppercase, like “TemperatureBeforeConversion”.

File and function header comments

In addition to commenting behavior, code formatting issues and symbol naming conventions, your project will most likely benefit greatly from standardized file and function header comments too.

Ideally, the file header should identify the file, describe its purpose, and act as a table of contents listing all functions and data type definitions it contains. The file header comment should also identify the author of the code and any code changes made (including date and a short description of the changes made, and by whom).

If you use a version control system, you can usually let the version control system auto-inject a dynamically updated changelog in the file header, using a keyword substitution tag. The practice of using this capability is a major time saver and is strongly recommended.

Every function should be documented using a standardized function header comment too. This should include a description of the function, its behavior, intended use, and document any input and output parameters, as well as any dependencies and side-effects (such as a global variable being updated).

Summary

Using good coding standards, coding style, and code formatting not only improve the readability, understandability, and maintainability of your code. It also makes you a better developer, separating you from the “cowboy hacker” crowd.

While it is unlikely your source code will ever read like a Shakespeare novel, you may want to make your code beautiful and read well – it pays off!

Do you want to learn more on great embedded tools for ARM Cortex C/C++ development? Read this whitepaper:

Read our ARM development  whitepaper!

Topics: editing, Software quality, Embedded Software Development