Wednesday, 19 July 2017

Bracket Like An Egyptian

Cheesy 80s pop reference, check! OK, on to serious business.

Languages such as C (and all its incarnations such as C++, C#, et al), Java, JavaScript and PHP share very similar syntaxes. And some of the most ubiquitous features in the syntax are curly brackets and semi-colons.

And today, I'm going to discuss curly brackets. Specifically, placement of curly brackets. There are mainly two conventions, and variations on each one. For a more comprehensive listing, check out the Wikipedia entry at https://en.wikipedia.org/wiki/Indent_style. Every coder has a preferred style, regardless of the one imposed by technical specifications in his or her day job.

My personal preference is this, and it's a pretty old style. Some call it the Allman style, after Eric Allman. I have no idea why I prefer it this way, but it's probably more out of habit than anything, and the style I default to when IDEs and technical specs aren't imposing a preferred style on me. In this style, the opening and closing curly brackets are positioned on their own line, on the left.
if (x == y)
{
    //code here
}


The other style is known as the K&R style, named after Brian Kerningham and Dennis Ritchie. Kerningham & Ritchie, geddit?

In this style, the opening bracket is positioned on the same line as the opening control statement (be it an If, For, While or function) while the closing bracket occupies its own line...
if (x == y) {
    //code here
}


...unless there's an Else condition or something.
if (x == y) {
    //code here
} else {
    //code here
}


Fun fact: in such a case, this is known as a Cuddled Else!

Watch the hands!

The K&R style is also known slangily as Egyptian Brackets. Because, if the brackets were hands, the pose would resemble a very stereotypical Egyptian dance pose. It's also the style IDEs such as Eclipse and Visual Studio, and text editors such as Atom and Sublime Text Editor, impose upon its users.

Egyptian Brackets are mostly preferred for a couple reasons.

Left? Right?

Aesthetics - someone I know claims that the way it reads is more natural. The whole right-to-left thing. Personally, I can't see it. But... you know, whatevs.

Look at all the paper you save!

Saving line space - as this style does not involve the opening curly bracket taking up its own line, that makes less lines of code. And while it only saves one line per code block, I guess it all adds up. And a lecturer once told me printing out a hardcopy of code using Egyptian Brackets would ultimately save paper.

Where should the brackets go?

Doesn't really matter to a machine, does it? Ultimately, it winds up in the compiler. Or interpreter. The only real difference style makes is when you're coding within a team and need to maintain consistency. Really, who cares about saving line space these days?

That's all for now. I'll be brack!
T___T

No comments:

Post a Comment