When you start to read more and more about software development, you frequently come across the phrase "clean code". In its purest form, this is code that's easy for other people to read. It's expressive and beautiful, and you can easily discern its intent simply by looking at it.

Writing clean code is easier said than done.

Whether you're an Arduino tinkerer, or you're building Raspberry Pi applications with Python, or you're even a web developer, there are some useful tips to follow that'll make your code easier to read by others. Here's what you need to know.

Be Consistent

Perhaps the first, and most obvious tip, is to be consistent in what you do. A good example of this is following the same patterns when naming functions and variables. You should pick a naming convention, and stick with it.

So, what naming convention should you use?

Well, if you're writing Python for Raspberry Pi, the answer is clear. The PEP-8 standard (the barometer for good, clean Python code) says that variable names should be in lowercase, with each word separated by an underscore. For example: gpio_input and moisture_sensor_reading.

cleancode-arduino

The Arduino style guide implicitly states you should write your variables in what's known as Camel Case. Here, words aren't separated by anything, but the first letter of each word is capitalized, except for the first word. For example: buttonPressed and temperatureReading.

There are, of course, other styles of variable naming. The above is simply that is recommended by the official style guides. But whatever you choose, make sure you stick by it, and use the same naming convention throughout your program.

Write Meaningful Comments

Comments are a great way of explaining what your program does. You can state what each function does and each variable represents in your own words. This makes it easy for a third-party to read your code, but also makes your code easier to maintain, as you ultimately understand it better.

But if you don't write your comments in a way that's obvious, and expressive, then you might not as well bother.

When writing comments, you should try and explain the why of the code, in addition to the how. Try and make the intent abundantly clear, and say something about the code that it can't say itself. So, rather than:

// update reading

Consider writing:

// Update the number of times the laser beam has been broken, before tweeting it out

Make sure you write in full, grammatically correct sentences. In addition, the PEP-8 standard for Python says you should always write your comments and variables in English. This makes it easier for others to collaborate with you, should you decide to release your code as open source, as English is pretty much the lingua franca of software development.

The Arduino style guide goes even further, and says you must comment every code block, every for loop, and every variable declaration.

Personally, I think that's a bit extreme. If you're writing verbose, expressive variable names, then your code is already self documenting. That said, don't hesitate to add comments where you think they're needed. Use your own good judgement.

Simplify Your Code

When you're learning to develop for the first time, you're often filled with an immense rush of enthusiasm. You read everything you can about your chosen language, framework, or platform. You start encountering concepts you never knew before, and you're all too eager to use them in your own code.

Things like ternary operators, which allow you to condense the logic of an "if statement" such as this one:

        
int x = 5;
if ( x < 10) {
 y = 1;
else {
 y = 0;
}

Into a single line, like this:

        int x = 5; 
int y = (x < 10) ? 1 : 0;
printf("%i\n", y);

Ternary operators are certainly cool, and I encourage you to read up on them. But when you're writing code that's easy for others to read, they're best avoided. That's just one example, though.

The Arduino style guide also encourages you to avoid pointers, #define statements, and data types other than the standard: boolean, char, byte, int, unsigned int, long, unsigned long, float, double, string, array and void. You should avoid data types like uint8_t, as these are less commonly used, not explained in the documentation, and not terribly terse.

Indent, and Take Advantage of Whitespace

When it comes to writing clean code, Python users are at an advantage, as the standard Python interpreter mandates that all code must be sensibly structured and indented. If you don't indent after each function and class declaration, and conditional statement, your program simply won't run.

cleancode-python

On Arduino, there's nothing stopping you from writing unstructured, compacted code. This, ultimately, is hard to read and hard to maintain.

But there's nothing stopping you from structuring your code better, either.

First, establish how much you're going to indent by. You should use the tab key judiciously, as each text editor treats the ASCII code for tab differently, and if you're sharing your code with someone else, there's a chance they can inadvertently introduce inconsistencies into your indentation. These inconsistencies can break your program, particularly if you're using a whitespace-sensitive language like CoffeeScript or Python. This article from OpenSourceHacker explains in more detail why the tab key should be avoided.

cleancode-tab

I tend to use four spaces for each indent, but the overall number is up to you. Just so long as you're consistent.

You can configure your IDE and text editor to treat each tab as a set number of spaces, however, allowing you to use the tab key without the risk of introducing problems. If you use Sublime Text 2, check out their official documentation. If you use Vim, just edit your .vimrc file with these lines. The Arduino editor automatically does this for you, and inserts two spaces whenever you press tab.

Then, you simply need to know where to indent your code. As a good rule of thumb, you should always indent after each function declaration, and after each if, else, for, while, switch, and case statement.

Many editors come with the ability to indent whole blocks of code at once. If you use Sublime Text 2, you can set up a hotkey or keystroke combination. Otherwise, you can use the default combination, which (on OS X) is Cmd+[.  In the Arduino editor, you can fix your file's indentation automatically by pressing Ctrl+T on Windows and Linux, and Cmd+T on OS X.

It entirely depends on your editor, so read the manual!

Don't Repeat Yourself

One of the most important mantras of good software development is don't repeat yourself, which is often shortened to DRY.

Writing DRY code is incredibly important, as it ensures that the logic of your program is consistent, allows you to make a change in once place and have it reflected globally, and you spend less time writing the same thing again and again.

The best way to stay DRY is with a liberal and generous use of functions – encapsulating a repeated task with a block of code you can call again and again – and ensuring that each one is distinct and well written.

cleancode-dry

A good function is short; the PEP-8 guide says little about function length, but Clean Code: A Handbook of Agile Software Craftsmanship by Bob Martin (highly recommended) says that "functions should hardly ever be 20 lines long". Preferably, they'd be even shorter than that.

Functions should also do exactly one thing. Need a function that does two things? Write two functions.

These tips make it easy to follow the flow of a program, and to ultimately debug it if need be. There's also an added benefit for Arduino users, who are tightly constrained by storage limitations, as redundancies are removed. This results in smaller programs.

Be Explicit

Another important mantra of software development is "explicit is better than implicit". It means that your code should pretty much shout what it's doing at the first glance. The Arduino style guide says that thing like this should be avoided:

        if(buttonPressed){ 
 doSomething();
}

Rather, you should make it obvious what's happening. Instead, write something like this:

        if (buttonPressed == True){ 
 doSomething();
}

Go Out And Code (Well)

Writing clean code is surprisingly simple. You merely have to be consistent in everything you do, avoid redundancies, and be explicit. Remember, clean code is merely code that's readable.

There's a lot of great reading material on this subject. A great starting point is Arduino tutorial and API style guides, followed by the PEP-8 standard if you're building Python apps for the Raspberry Pi. If you're using another language (like Javascript on the Tessel board), check Google for an official style guide.

If you're looking for a more academic reading on the subject, check out Clean Code: A Handbook of Agile Software Craftsmanship by Bob Martin. I mentioned it earlier in this article, and it comes highly recommended. Although it uses Java to illustrate concepts, many of the ideas can be passed on to other languages, like Python and C for Arduino.

There's also some brilliant blog posts online that illustrate how to write good, descriptive, clean code. I recommend you check out "Clean, high quality code: a guide on how to become a better programmer" by Arash Arabi writing for butterfly.com.au, and "The Fundamentals of Writing Clean Code" by Chris Reynolds, writing for webdevstudios.com.

Although not explicitly related to clean code, it's also helpful to learn what functions and libraries are best avoided in your language of choice. For example, if you're learning PHP, you should avoid the "mysql" libraries, and if you're building physical products with Arduino, you should never use the Delay function.

Remember, code that's easier to read is easier to maintain. Plus, should you ever get stuck with something, it's easier for someone to read it and help you.

Do you have any tips for writing clean code? Did I miss anything? Tell me! Leave me a comment below, and let me know.

Photo Credits: Dry Bed (Premasagar), Little TAB Key (Kai Hendry), 2015 (Wikilogia)