tags:

views:

340

answers:

16

I generally will always write conditional code along the lines of

if (number==1) 
    name="a";
if (number==2)
    name="b";

no matter how short, although I find a fair chunk of people writing

if (number==1) name ="a";
if (number==2) name ="b"...

To me this seems inconsistent, and actually makes the code look messier.

What is the best way to do this?

+16  A: 

Coding styles are one of the most hotly debated topics (and often with religious fervor). There are lots of resources about this question, I'll try and find the links.

Either way, I am a fan of wrapping every such condition body with curly braces; my experience is that they make the body more visible and reduce the risk of errors if lines are added or omitted.

Uri
I use a bit of both styles, but if I use the two-line style I ALWAYS use { } open and closing braces. Sometimes an if structure can be on a single line. I do this with property manipulations, for example.
Chris Kaminski
i tend to disagree. one line if statements don't need curly braces because they're a single statement. It's super easy to see if braces are needed when adding statements.
Atømix
My experience from teaching C is that many mistakes came from students not adding the braces and then suffering the consequences of careless addition and removal. You'd be surprised at how students mess this up. And from what I've seen, they do it in senior year too, so they may very well be doing it in the real world.
Uri
I agree, and I appreciate your a) not being religious about it, and b) not leaving it to the "real world" to teach such practical stuff, because often when students hit the real world they figure their job is to promote the lastest stuff they learned in school.
Mike Dunlavey
@Mike: Thank you! I'm also glad you were able to read this thread, ever since SO started reorganizing comments lots of comment threads have gotten messed up:)
Uri
+1  A: 

I do the same (in java) and I always add curly braces, even if it's only one line, it's no work at all and eliminates one classic source for bugs.

André
+8  A: 

I prefer your first option, but better yet:

if (number == 1) { 
    name = "a";
}
if (number == 2) {
    name = "b";
}

a little longer at simple view, but i won't have to add brackets when the if get larger than one line (very often, i think)

Jhonny D. Cano -Leftware-
I always use this format. In my opinion, it's the most readable and allows for the easiest editing in the future.
Thomas Owens
Your brace are on the wrong line... =P
GMan
lol you are wasting one LOC
Jhonny D. Cano -Leftware-
+1  A: 

This is, of course, purely a matter of style. Generally speaking, extra space is comfortable. However, there are times when it seems appropriate to condense these things down. Generally, I'll only do this when it's a variable assignment, never anything else.

I always prefer to have code look like it should, meaning, single if statements should always look the same. I usually even leave in braces just so it's clear what's what.

Tony k
+1  A: 

I only use the first option. Easier to read, and easier to set breakpoints in the conditional.

jfclavette
+7  A: 

I always write my conditionals the same:

if (number == 1)
{
    name = "a";
}
else if (number == 2)
{
    name = "b";
}

It's easy to read and consistent. Consistent with if statements that have more than one statement, etc...


Edit

To expand on this, I try to follow this rule:

Each line does one thing.

That is, each line should execute one statement (and scope should be easily visible). So I do not prefer:

if (number==1) name ="a";

Because two things are happening on one line, which makes reading and debugging more difficult than it should be. So I would move to:

if (number==1)
    name ="a";

But this has the problem that it's inconsistent with a multi-statement if. That's why (as other have stated) it's good to place brackets around things:

if (number==1)
{
    name ="a";
}

The reason I prefer the '{' on it's own line is that when I scan the code, I can quickly identify where a scope begins and ends. It also follows the one statement rule, since having 'if' and '{' does an if statement and starts a new scope.

I do not think that, "it saves vertical whitespace" is a good enough reason to skip readability and good formatting (both {}'s on the same column == sexy). This is because considering the resolution of today's monitors, you don't need to struggle to view code.

GMan
+2  A: 

I prefer:

if (number==1) { 
    name="a";
}
if (number==2) name="b";

Whenever I use a bracket I start a newline.

Rob
You prefer inconsistency? Why would the second if be differently formatted than the first one?
Graeme Perrow
think he's implied he prefers the first style to the second in his example.
maxp
A: 

it has negligible difference in code readability, do whatever you want. write good code, let your IDE figure out how it should look.

Dustin Getz
+2  A: 

I am using the following style.

if (number == 1) 
{
   name = "a";
}
else if (number == 2)
{
   name = "b";
}

This avoids errors if you insert a new line.

if (number == 1) 
   DoSomething();
   name = "a";

Now name = "a"; is no longer conditional. Currently I am thinking about changing to the following style.

if (number == 1) {
   name = "a";
}

This way the text structure reflects more closly the control structure but I am still thinking about that.

Daniel Brückner
+2  A: 

I'm a firm believer that if you're going to put the statement on a line after the conditional, wrap the thing in braces. To give a specific example of @Daniel's point, if I'm debugging this:

if (number==1) 
    name="a";
if (number==2)
    name="b";

... I'm going to be sorely tempted to do this:

if (number==1) 
    print "Hit the first conditional\n";
    name="a";
if (number==2)
    print "No, hit the second conditional\n";
    name="b";

... and runtime hilarity ensues.

I'll occasionally put a single-line command on the same line as the "if" statement if it's something obvious and simple, like "if (inputVar == null) return;". But as a general rule, if I'm indenting individual commands (as opposed to a single big command spanning multiple lines)*, I always want them enclosed in braces. I get myself into less trouble that way.

* -- Okay, technically, those single-command if statements are indeed a single command spanning multiple lines. But if I accidentally insert a command into the middle of a multi-line method call, the compiler will barf before I can get too confused.

BlairHippo
+2  A: 

Personally, I love laying out conditionals on a single line, IF and ONLY IF, there are a set of them which I want to compare easily.

if      (iTerm >= Ps.missed_runs)   iTerm -= Ps.missed_runs;
else if (iTerm <= Ps.missed_runs)   iTerm += Ps.missed_runs;
else                                iTerm  = 0;

Here I can clearly see what is the same, and what is different. Compare with this:

if (iTerm >= Ps.missed_runs) {
    iTerm -= Ps.missed_runs;
} else if (iTerm >= Ps.missed_runs) {
    iTerm += Ps.missed_runs;
} else {
    iTerm  = 0;
}

Now the comparisons are distant from eachother, and not aligned to a column. It is harder for the eye to spot a bug.

P.S. did you notice the deliberate bug in the second code example?

Hugo

Rocketmagnet
if you started a new line after each '}' then it would be a comprimise between the two. I believe all versions of vstudio will do this by default.
maxp
A: 

Microsoft C# Best Practices state to use curly braces for single line conditionals. I find this much more readable, personally. I tend toward this habit in other languages as well, when language-appropriate.

if (myVar == 0)
{
    return false;
}
Demi
+2  A: 

Python pretty much forces you to, so yes - conditional code always goes on a new line.

if number == 1:
    name = "a"
elif number == 2:
    name = "b"
else:
    raise ValueError()
Adam
That is actually not true, it is considered good style but you can put it in the same line as well.
André
I know, hence the "pretty much". The only time I put it on the same line is when I'm trying to win a competition to see who can do a particular task in the smallest amount of bytes.
Adam
++ on general principles :-) Actually, there's another issue at work. As you get older you'll notice that you can't handle very high-resolution displays, so you prefer not to waste pixels or push code off the bottom of your screen. Formatting is important, but having less code to read at one time is not the same as readability.
Mike Dunlavey
A: 

OK, I need some downvotes. This is really ugly, but I think it has a good reason:

 if (false){}
else if (variable == aValue){
  ... code ...
}
else if (variable == anotherValue){
  ... code ...
}
... more cases ...
else {
  ... code ...
}

The reason is that no branch (other than else) is different from any other, so it is easy to re-order them or insert a new one at the beginning.

In fact, if I'm generating this code from another program, it really simplifies the generator.

Mike Dunlavey
Eugh, that's really horrible! I can understand your reasoning but I'd have thought the smelliness of the code would outweigh any potential benefit of being able to easily shift the clauses around.
Adam
@Adam: I guess I think smelliness is in the nose of the smeller. I've coded in assembler for lots of machines, and in Fortran, Lisp, Cobol. None of these would win any points from Simon Cowles. I think form follows function.
Mike Dunlavey
+1  A: 

I will just about always put it on a different line, but I'm somewhat flexible. If code is more readable on the same line due to the fact that many statements in a row are very similar, I might do it on a single line to help demonstrate the similarity, but I'd be looking for a way to eliminate the similarities by refactoring instead.

Bill K
+1  A: 

When putting conditionals on a single line, I use the single line format:

toggled = (on == true ) ? true : false;

However, this doesn't work when you have multiple cases, where I might use a switch statement:

switch ( number ) {
  case 1: a;
   break;

  case 2: b;
   break;
    a;
}

For your specific example, I would do this:

if ( number == 1 ) {
  name = "a";
} else if ( number == 2 ) {
  name = "b";
}

I like the extra space in between values and parentheses as it helps keep everything clean by kind of highlighting them.

scottm