Have you ever seen this meme?

Two kinds of developers based on brace placement

I've seen several variations, but the main joke is the same: Programmers often care a lot about the way their code looks, and we can get very attached to a particular style.

But does it matter? will caring about the way your code looks make you a better developer? a better team player? can it help you become a more senior developer or get a better job?

Short answer: Yes. Keep reading for the longer, and hopefully entertaining, answer.

Does It Really Matter Though?

Code formatting is one of the things I repeatedly saw newbie developers neglect. My students were so focused trying to make their code work that didn't care too much about the way the code looked like - as long as it worked.

That's completely understandable at first, but I'm always very quick to introduce the idea that we want to write code for other human beings; not for computers. This can be an odd idea. After all, we want the computer to read and execute our code in the end right?

Well, the computer is going to execute your code, but it'll use a binary representation of it and not exactly what you wrote. The only ones reading what you write are going to be human beings. Computers don't care about how your code looks like as long as they can run it.

"Ok. Fine." You say. "The computer doesn't care about that. Why should we then?". Great question! Let's think about how many times a line of code is written vs how many times it is read. You write a line of code once, and it's read when:

  • Someone code-reviews your code
  • Someone needs to update your code to add more functionality around it or to fix a bug.
  • Someone needs to re-use your code in another system.

Spoiler alert: "Someone", unsurprisingly, means someone else, but it also means future you!

Past vinicio hits future vinicio with bad code

Don't believe me? That's ok. I came prepared with some quotes from the greatest. In Clean Code, Steve Martin states that "The ratio of time spent reading vs. writing [code] is well over 10:1. We are constantly reading old code as part of the effort to write new code."

In Code Complete, Steve McConnell mentions a 1983 study that suggests "programmers spend 50 to 60 percent of their time trying to understand the code they have to maintain" (page 842). I tried looking for a more recent study, but my Google-fu was not able to find anything 💔.

What does that mean? To me, it means that:

Developers should put more effort into learning how to write code that's easy to read and less effort into learning how to write code that's easy to...write.

So What?

I'm not going to lie, I went through a phase where one of my biggest goals was to write the "coolest" code I could think of; usually one-liners. I didn't care much about how readable the code was. When I was introduced to code readability ideas, I remember thinking "Ok, my code can be easier to read. So WHAT?"

Well, I eventually realized that there were a lot of "whats". Everything around a piece of code seems to improve if the code it's easier to read. The code will be easier to understand, debug, modify, extend, and review.

But wait, there is more; It's also easier to write correct code that works if you can easily read what you are writing. Algorithmic thinking is hard enough to make our lives harder by writing cryptic code.

Let me close this section with a quote from an old book called The Elements of Programming Style. Kernighan and Plauger wrote, "The self-discipline of writing [code] cleanly the first time increases your chances of getting it right and eases the task of fixing it if it's not." (page 155).

I find it's fascinating that the idea of writing clean code was being discussed over 40 years ago by them. Isn't that amazing!? (No need to answer that question. I know you are silently nodding)

What would be "Good Code Formatting"?

Entire books could be, and have been, written about this topic. I'm planning on writing a series of articles myself ;), but Code Complete comes again to our rescue. Good code layout should:

  • Accurately represent the logical structure of the code
  • Consistently represent the logical structure of the code
  • Improve readability
  • Withstand modifications

McConnell claims that it's useful to keep these principles in mind when discussing specifics about code formatting. I think all of his points are very valuable and need to be balanced.

Consistency avoids rules with tons of exceptions. Withstanding modifications ensures making changes is not overly cumbersome, and we have been talking about readability for about 700 words so far! haha!

However, the most important criteria, in my opinion, is the first one. McConnell even gives this principle a special name:

The Fundamental Theorem of Formatting

McConnel writes: "Good layout should accurately represent the logical structure of the code". I want to spend a little bit of time talking about why I think this is important. I'm going to start by using real code written by one student of mine - with permission of course ;)

function checkLocalStorage() {
if (localStorage.stringyProducts) {
    
    //create instances 
    var retrievedProducts = JSON.parse(localStorage.getItem('stringyProducts'));
    console.log('retrieved item', retrievedProducts);
    retrievedProducts.forEach(function(productItem){
        new Products(productItem.name, productItem.views, productItem.votes);
    })
    drawChart();
        //  = JSON.parse(localStorage.retrievedProducts);
    } else {
        names.forEach(function(productItem){
            new Products(productItem);
        });
            
         } 
    } 

If you do a quick-ish scan on the code, can you identify which block is being closed by lines 17 and 18? Maybe you can; maybe you can't, but I believe that it's harder than it should be.

Initially, when I was selecting the fragment to paste in this article, I thought the function was longer. I didn't realize it was closed on line 18 until I double-checked the code I wanted to copy.

Now, let's take a look at the same code with some small changes I made:

function checkLocalStorage() {
    if (localStorage.stringyProducts) {   
	    //create instances 
	    var retrievedProducts = JSON.parse(localStorage.getItem('stringyProducts'));
	    console.log('retrieved item', retrievedProducts);
	
	    retrievedProducts.forEach(function(productItem){
	        new Products(productItem.name, productItem.views, productItem.votes);
	    })
	    drawChart();
    } else {
      names.forEach(function(productItem){
          new Products(productItem);
      });           
    }  
} 

I didn't want to change too much, so I just played with some spacing and indentation for a couple of minutes. I think now it's easier to grasp that line 17 is matching the else statement and that line 18 is matching the entire function.

I also added an empty line on line 6 to make the forEach function easier to distinguish from the rest of the code. What do you think? Does that seem easier to read and understand?

I had to fabricate the next example since I couldn't find it in my student's code ( yay!? ). This is one of the classical "textbook" examples on why formatting matters, and I have seen variations on it throughout the years - sometimes in my own....code:

if(condition)
	console.log('Kali is the heartbeat of the universe');
    console.log('Khal is sweet');
	console.log('Kali is shy');
	console.log('Khal is brave');

Can you scan the code and tell me which lines will be executed if condition is true? Maybe you can, but what about when you are reading a larger codebase?; or trying to complete a task that was estimated to be 2-4 hours and you are already on the fourth hour AND haven't made much progress? (That may or may not have been a real example)

Would it be easier to read something like this?

if(condition) {
	console.log('Kali is the heartbeat of the universe');
}

console.log('Khal is sweet');
console.log('Kali is shy');
console.log('Khal is brave');

Again, the change took me less than a minute, and it greatly improves the code's readability. These small changes also make the code easier to modify. If we need to add more statements to the if's body, we don't need to spend those extra seconds adding the braces. More importantly, we eliminate the risk of forgetting to add the braces.

These may seem like small wins, and they may be, but remember that withstanding modifications was one of the criteria for a good layout. We'll go into much more detail in a series of articles I'm working on, but I hope this illustrates how small changes can make code easier to read and understand.

Do you have any &!@~; proof all of this will make me a better developer?

I'm glad you asked!. I realized academic papers can be very expensive, but I was able to find a study referenced by McConnell in Code Complete. It is called Empirical Studies of Programming Knowledge by Kate Ehrlich and Elliot Soloway.

In the study, Ehrlich and Soloway were trying to explore how developers read and understand programs. They designed two experiments:

  • Fill-in-the-Blank: Asked novice and expert developers to complete pieces of code that had one missing line.
  • Recall: Asked expert developers to remember as much as they could about a piece of code in 3 20-second windows.

In both experiments, they built two versions of every piece of code the developers analyzed. One was built using the best practices common at the time, and the second version changed as little as possible to make the code harder to read.

I'll go into much more detail in a video I'm working on 😉, so let's jump right into some of their findings. I want to highlight 2 of their conclusions. They wrote:

  • "When the test programs were not plan-like (i.e., the plan composition violated some rule of programming discourse) then the performance of advanced programmers was reduced to essentially that of the novice programmers" (page 608)
  • "The results point to the fragility of programming expertise: advanced programmers have strong expectations about what programs should look like, and when those expectations are violated - in seemingly innocuous ways - their performance drops drastically (page 608)"

 BTW, innocuous means "not harmful or offensive". I...googled it. Anyway; This study tells us that, indeed, code that's easy to read and understand will increase your performance as a developer. However, I want to close this article by focusing on the second quote...

Consistency is key. Be open-minded.

Meme: A bird refuses to hear another bird about style

There are very few "objective" style rules, but a lot of them are subjective. Often, code that you can easily read is code that you like and/or are used to.

Notice how Soloway and Ehrlich write "expectations about what programs should look like". A lot of the discomfort we might feel when we are exploring a new style comes from our expectations and not from the new style being inherently "wrong". That's something important to keep in mind when you are discussing style rules online or in a team.

Please don't insult somebody else's style.

I know I've seen my fair share of Twitter insults about line endings and brace positioning. Professionally, I've been part of design discussions where some arguments boil down to "I prefer to code it this way because it makes more sense to me and I like it". That reasoning is valid.

As long as nobody in the team is left unheard and you arrive at a reasonable consensus, then your performance should increase as you become more familiar with the team's style if you are consistent with it.

In summary

Writing readable code is a vital skill for a developer, but what's easy to read can be subjective. As long as you keep an open mind and are willing to improve your style, you'll be heading in the right direction.

We've only covered the tip of the iceberg here. I'll dive into specifics in future articles. Sounds interesting? please subscribe to my newsletter using the form below and get excited for what's to come!

Works Cited

Martin, Robert. Clean Code. Pearson Education, 2008. Kindle Edition.

McConnell, Steve. Code Complete. 2nd ed. Microsoft Press, 2004. Print.

Kernighan, Brian W., and P. J. Plauger. The Elements of Programming Style. McGraw-Hill, 1974. Ebook.

Soloway, Elliot, and Kate Ehrlich. “Empirical Studies of Programming Knowledge.” IEEE Transactions on Software Engineering, SE-10, no. 5, Sept. 1984, pp. 595–609.