Requiring Code Block Braces

Published on March 3, 2010

One of the things I most appreciate about Perl is that it requires code blocks to be surrounded by curly braces. In my mind, this is particularly important with nested if-else statements. Many programming languages don’t require braces to surround code blocks, so nested conditionals can quickly become unreadable and much harder to maintain. Let’s take a look at an example:

if (something)
    if (another_thing)
        if (yet_another_thing)

Note that the outer if-statement doesn’t have corresponding curly braces. As surprising as it may seem, this is completely legal code in many languages. In my opinion, this is a dangerous programming practice. If I wanted to add additional logic to the contents of the outer if block, I would have to remember to put the appropriate braces in place.

Had I attempted to use this code in a Perl script, the interpreter would have complained immediately, even if warnings and strict parsing were both disabled! This kind of safety checking prevents me from shooting myself in the foot. Some may complain that requiring braces makes programming slightly more inefficient from a productivity standpoint. My response to that is that any code editor worth its salt can insert the braces for you. My favorite editor, SlickEdit, even supports dynamic brace surrounding, a feature I truly appreciate. It’s a shame that more programming languages don’t enforce this kind of safety net. Hopefully future languages will keep small matters like this in mind.



Just use Python. Don’t need no steeking curly braces.

Comments are closed.

Copyright © 2004-2019 Jonah Bishop. Hosted by DreamHost.