A case for missing curly braces
Many times as a deadline approach, we cut corners. We think in terms of “the less amount of keys pressed the better,” because we need to finish our code on time. At first, we tend to eliminate the curly braces when defining a block of code, specially in “if” and loop statements.
if(amount >= 500) result = true;
The problem with this approach is that we are thinking about the immediate deadline, in what we are coding right now. We forget two things: that we are not the owners of our code, and that someone will have to dig into the code to add a new feature or fix a defect later.
We forget from time to time that we are coding for a company or for a client and not for ourselves. We are the owners of the code at the moment we are coding, but it will stop being ours the moment we deliver it or finish it. The important thing is to deliver high quality code that is easy to maintain and easy to follow. How many times do we say to ourselves, “What the [insert curse word here] I wrote here? What was I thinking?!”
If this happened to us, if we wrote a piece of code, imagine what would happen to others. Sometimes the “new guy” is the one that makes a mess in the code base, as follows:
if(amount >= 500) result = true; sendEmail(emailAddress);
In this sample code, the “new guy” wants to send an email if the condition of the if statement is reached. In reality, the code will send the email each time, not taking in account if the condition is met or not.
if(amount >= 500) { result = true; sendEmail(emailAddress); }
Adding the curly braces will tell the compiler, as well as to any other programmer, that sending the email is part of the if statement block.
All this mess can be prevented if we do 2 to 4 additional keystrokes per block statement. Other programmers will appreciate it. Your future self will appreciate it… And maybe the whole world!