in General Coding, Learning Tips

Format Your Code for People, Not Machines

One of the many things you’ll learn as a new programmer is that the placement of your code in a document is mostly irrelevant from the perspective of the computer. For example, compare this JavaScript snippet:

To this one:

From the perspective of the computer, they are identical. To be clear, however, there are several languages, such as Python, or pre-compilers, such as HAML, in which elements such as indentation do matter.

When it comes being cognizant of the human perspective of coding, my favorite language is Ruby. Yukihiro “Matz” Matsumoto, the creator of Ruby, explains:

Often people, especially computer engineers, focus on the machines. They think, “By doing this, the machine will run faster. By doing this, the machine will run more effectively. By doing this, the machine will something something something.” They are focusing on machines. But in fact we need to focus on humans, on how humans care about doing programming or operating the application of the machines. We are the masters. They are the slaves.

There is a great presentation on Ruby and the importance of well-formatted code, “Beautiful Ruby Code Formatting”, by Florent Guilleux, which I think truly embodies this thinking.


He starts off his talk with a great quote from the inimitable Robert “Uncle Bob” Martin:

Code formatting is important. It is too important to ignore it and it is too important to treat religiously. Code formatting is about communication, and communication is the professional developer’s first order of business.

Guilleux has several great examples in his talk of good formatting.

Here are two of my favorites:

This is a great example showing the importance of proper indentation to make scannability easier.

This is a great example showing the importance of proper indentation to make scannability easier.

I'd actually never seen a RegEx statement formatting like this before.  I think it has a huge impact in being able to understand the code.

I’d actually never seen a RegEx statement formatting like this before. I think it has a huge impact in being able to understand the code.

I think these examples speak for themselves. Simply spending a little more time thinking about your code in terms of its scannability and usability for others who will be reading it (as well as for yourself when returning to the code much later and trying to remember what the code was supposed to do) will go a long way.