Is it better to use braces or no braces for single-line if blocks? [closed]
Asked Answered
B

1

5

What is better coding practice for single-line code blocks following an if statement - braces or no braces? Just to avoid too many "Well, it depends on what language you're using..." answers, let's say for C#. In other words, which is better:

if(somecondition)
{
  singleLineStatement;
}

Or

if(somecondition)
  singleLineStatement;
Backwards answered 3/11, 2010 at 14:8 Comment(0)
I
9

I think the consensus is to use braces. If you omit the braces there is a risk that someone will add an extra line without noticing the missing braces.

Imbecilic answered 3/11, 2010 at 14:10 Comment(2)
I make my if and else match. If the if is multiline and the else is single, they'll both be bracketed. If I have two single line components in the if and else, then they'll both generally* be sans-braces. I don't feel the need to completely idiot-proof the code, because they keep making better idiots. (*) There are exceptions if braces help readability, such as when a single statement spans multiple lines.Functionalism
@AnthonyPegram I tend to do that as well. The hardcore support for superfluous braces I occasionally encounter is quite humorous.Arachne

© 2022 - 2024 — McMap. All rights reserved.