Brace placement

Since the C language appeared in the 70’s, holy wars have been raged about how the code should be formatted.  Since then, these disputes have inherited also to languages borrowing the C-esque language style, such as Java, JavaScript and C#.

Most new languages come with a specified style guideline, which promotes consistency and collaboration. Sun attempted this by publishing the Code Conventions for the Java Programming Language.  However, they had the burden of decades of existing practice, and so the debate continued.

One of the biggest questions is the positioning of braces:  should they be on a separate line or on the same line as the statement. This is largely a matter of personal taste: some like sparser code, some denser.

I have come across one case which makes a clear distinction to the benefit of one convention.  It’s not a common case, but I have come across it in production code.

Consider the following code (you don’t need to read it through):

I agree it’s not very clean code, but I’ve seen even longer variants in production code.  And I’ve wondered for a long while why it doesn’t work like I expected it to.

I hadn’t noticed that one of the if‘s did not have an else preceding it.

Consider the same code with braces on the same line as the statement:

The code flow is much clearer in the latter formatting due to the added newline when a new if-statement occurs. This is a clear benefit of same-line placement style, and in my opinion enough to weigh on the side of using that style.

This entry was posted in Coding, Style and tagged , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s