Braces with Control Statements

Question
I’m writing an if or for construct and the body contains a single statement. Is it okay if I omit the curly braces?

Answer
No, it’s not best practice. Use braces for all block statements, including:
• if
• for
• while
• do…while
• try…catch…finally

Examples

// Incorrect. Braces are missing.
if (someCondition)
  doWork();

/* Incorrect.
 * Braces are missing.
 * Multiple statements are on a single line.
 */
if (someCondition) doWork();

/* Incorrect.
 * Braces are present, but...
 * Multiple statements are on a single line.
 */
if (someCondition) { doWork(); }

// Correct.
if (someCondition) {
  doWork();
}

Leave a Reply

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

WordPress.com Logo

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

Google+ photo

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

Twitter picture

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

Facebook photo

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

Connecting to %s