Coding style

2 minute read

Published:

Coding style is a matter of taste.

The trouble is, different people on a software team have different tastes.

Forcing a style

When I first taught a coding course, I decided that students needed to adhere to a style guide that I set. I discussed it with the students, and there was contention even from the start: some preferred 2-space tab stops while others preferred 4-space tab stops.

So the style I forced on them used 3-space tab stops, a healthy compromise.

Or so I thought.

The students hated it, and hated me because of it.

Lesson learnt.

Forcing agreement on a style

The next time I taught the same course, I set a meta-style: the teams of students had to agree amongst themselves on a coding style, and the style had to include:

  • Number of spaces to use in tab stops.
  • The way variables, classes, constants, and methods would be named.
  • The structure of the program they’d use.

This approach was much more successful. Instead of hating me, they hated their teammates.

Other coding styles

There are lots of coding styles around and they vary by platform, project, and language.

The Linux kernel coding style is interesting: it says that the indentation tab stops should be 8 spaces!

Curly brace alignment

Apart from consistent indentation of code, the most important for me is where the curly braces that indicate code blocks line up.

One approach is:

public static main(String[] arguments) {

}

which is the Java style.

Another is

public static main(String[] arguments) 
{

}

which is my preferred style… except that some languages (JavaScript and Go) are either problematic (JavaScript will auto-insert a semi-colon if it thinks you’ve forgotten it) or forced (Go forces opening brace on the same line).

Why do I prefer this second approach? Primarily it’s because I find it easier to see matching braces. Provided the code is otherwise indented properly, I can just scan up and down to find the match. Otherwise I have to scan up and to the right… by some unknown amount.

It’s a minor, minor point, but that’s my preference.

This post on the Software Engineering StackExchange site gives some more detailed commentary on it.

Whichever style you use, be consistent.