3

I was recently involved in an argument with a coworker involving one line if statements and wanted to see what stackoverflow thought.

Do you feel that the statement should be written as:

if(condition)
{
     statement = new assignment;
}

OR

if(condition)
    statement=new assignment;

please provide a good reason for your decision.

Thomas Owens
  • 114,398
  • 98
  • 311
  • 431
ErnieStings
  • 6,333
  • 19
  • 47
  • 54
  • 2
    Duplicate: http://stackoverflow.com/questions/97506/formatting-of-if-statements, http://stackoverflow.com/questions/691476/are-singleline-if-statements-or-if-statements-without-bad-practice, http://stackoverflow.com/questions/779332/do-you-put-conditional-code-on-a-new-line-or-only-sometimes, and many others. – Shog9 Sep 16 '09 at 18:47
  • 1
    By your edit you've totally changed the question ;-) – Michael Krelin - hacker Sep 16 '09 at 18:48
  • i looked through the edit history, and there were two edits after you asked your question: a retag, and a code formatting with an attempt to make it an actual question. the overall meaning did not change. – geowa4 Sep 16 '09 at 19:01
  • 1
    @geowa: Of course it did. The code "formatting" changed the nature of the question. The subject refers to "one-line if statements". The first example now takes *three* lines and the second example takes *two*. – Adam Robinson Sep 16 '09 at 19:06
  • @Adam: If you look at the original question, it was written out EXACTLY as it appears now. However the OP didn't have the code formatting set correctly, so it appeared as a *single* statement. I agree, the before and after edits change the meaning of the question, but from what was originally written (including format) I believe how it appears now is what the OP intended. – Alan Sep 16 '09 at 19:20
  • @Alan: You're correct, but I was responding to geowa stating that the edit didn't change the question, which it did. The prior question may not have been what the OP intended, but it WAS the question. – Adam Robinson Sep 16 '09 at 23:24

11 Answers11

20

if you should really use one line if

 if(condition) statement=new assignment;

will be better since its one line, it should contain one operation.

Cem Kalyoncu
  • 14,120
  • 4
  • 40
  • 62
  • 1
    +1, because basically, if you need braces, you don't write it in one line. – Michael Krelin - hacker Sep 16 '09 at 18:44
  • 1
    NEVER ever do this, please. This is pure cancer, if you have to debug. While debugging you never exactly know, if the condition is True and the statement was set! You always need to dopplecheck. Even worst if there is a break after the `if` ... There is surely a special place in Hell for people doing this. – VRage Nov 14 '18 at 07:34
  • 1
    That's just plain horrible to debug and it's absolutely not easier to read. – Andreas Nov 14 '18 at 09:33
  • The idea is to prevent people from adding statements to an if without braces. I personally use it only for break and continue and do not condone the use of if without braces. I think you need to upgrade your debugger if it cannot do two statements in a single line. – Cem Kalyoncu Nov 15 '18 at 08:46
15

I always use enclosing braces to reduce the risk that someone (including myself) will later introduce a bug by editing the code around the if statement without paying careful attention to which line(s) belong as part of the if-condition.

EDIT:

Here's a live example if this I just happened to come across in some old code:

if (form.validateUpload (messages, this))
    return getErrorOutcome (ctx, messages);
    if (LOG.isInfoEnabled ())
        LOG.info ("CREATING UPLOAD");

Notice how both "if" statements are in the main block of code but due to poor formatting, at first glance they appear to be nested. Sure any "good" programmer should quickly see what's happening, but why cause any unnecessary confusion?

Eric J.
  • 147,927
  • 63
  • 340
  • 553
  • This sort of **nested** IF statements are dangerous and should be avoided. But that does not mean **all** one liner if statements are bad. `if(somethingBad) return` or `if(something) doSomethingElse()` in a function body for example adds a great deal of readability IMO. – PrashanD Jul 29 '20 at 08:34
5

I've always been a fan of braces. If someone were to modify a oneline if statement like so:

if(condition) statement=new assignment;

to

if(condition)
statement = new assignment;
another statement;

You won't get the expected behavior.

Using the braces pretty much insures that if someone modifies an if statement, they'll make sure to put the right statements in the right place.

Alan
  • 45,915
  • 17
  • 113
  • 134
  • 13
    If somebody does that, they obviously don't understand the language. Doesn't this fall under basic competence? (sincerity intended) – John MacIntyre Sep 16 '09 at 18:46
  • 6
    Understanding the language and making typo's have nothing to do with one another. Adding braces *ensures* that the correct behavior happens regardless. – Alan Sep 16 '09 at 18:48
  • 3
    Maybe. Could be a junior programmer maintaining code well after it's first written. Could also be a senior programmer having a bad day. Why create an opportunity for someone to make a mistake? – Eric J. Sep 16 '09 at 18:49
  • 2
    So you suggest littering the code with many unnecessary braces. – Cem Kalyoncu Sep 16 '09 at 18:50
  • Eh, that depends on what the expected behavior was. If you have the first clue how your language works, you should expect the first statement to be conditionally executed and the second unconditionally. – Chuck Sep 16 '09 at 18:50
  • 1
    Yes, because we should expect that *EVERYONE* who touches our code will have a clue. – Alan Sep 16 '09 at 18:53
  • @Alan: What if somebody sticks the next line outside of the braces but expects it to still be conditionally executed? – Chuck Sep 16 '09 at 20:39
  • 1
    Then that person has introduced a bug. – Alan Sep 16 '09 at 21:02
  • 3
    @Alan - We can't idiot-proof our code. Anyone who doesn't know this kind of basic language behavior needs to learn the language, and fast. They obviously don't know it, and shouldn't be playing around with your code, and any bugs they introduce can a) be easily fixed by someone competent, and b) potentially teach them something that they apparently need to learn the hard way. I use the one-liner style, and have never fallen prey to this particular bug. It's such a widespread and widely warned against "gotcha" that no one falls for it anymore. – Chris Lutz Sep 16 '09 at 23:18
  • 2
    Defensive programming is like defensive driving. You don't need it until you're careening off a cliff due to someone else's mistake. – Jubal Sep 16 '09 at 23:32
  • 1
    @Chris: you can't make your code idiot-proof, but you *can* make it idiot resistant. We're not talking about spending hours and hours of work here. Most IDE's will auto complete braces for you, so adding braces after and if() statement requires at most one extra keystroke. Clearly braces is going to be group/personal preference, however the justification for using braces is sound: it prevents a relatively simple error. – Alan Sep 17 '09 at 15:28
4

This really depends on the coding style of your group. The group should have consistent coding standards. For my current group we always use:

if (condition) {
  statement = new assignment;
}

We do this to prevent mistakes caused by forgetting the braces after the if statement, such as:

if (condition)
   statement1;
   statement2; 
//statement2 is not part of the if statement, but it looks like it because of wrong indentation

Another group that I worked with until just recently always used this syntax for one-line if statements:

if (condition)
    statement1;

Personally I don't like this as much because it's less explicit; but the most important thing is to stick to a consistent coding standard for your group or project, so that code you write looks like code your co-workers write, and is just as easy to read for everyone in the group.

The conventions of your IDE or environment can provide a good basis for your coding standards, and may even be tailored to your group's style.

RMorrisey
  • 7,637
  • 9
  • 53
  • 71
1

I always do one-line if statements sans-brackets. The presence of brackets indicates (syntactically correctly) that "oh, I can do something else in here..." and I don't like the temptation. Anything that involves more than one statement should be broken up into multiple lines with proper brackets.

Adam Robinson
  • 182,639
  • 35
  • 285
  • 343
1
if(condition)
    statement=new assignment;

or

if(condition) statement=new assignment;
John MacIntyre
  • 12,910
  • 13
  • 67
  • 106
1
if (condition)
{
    statement = new assignment;
}

is what I would write. Namely because I like tidy code which saves time to read/edit/understand.

In very few cases I'd make an exception normally only when I'm quick and dirty coding something for debugging etc.

A one line if statement is always very easily corrupted by how the semicolon is placed.

capfu
  • 157
  • 1
  • 7
  • What defines "tidy code"? It is quite subjective. I think that placing the curly bracket after the if uses up a whole line unnecessarily. – jdg Dec 05 '18 at 19:48
0

I would go without the brackets.

The only reason you would need the brackets is if you had multiple statements inside the block.

Sounds like a waste of an argument though.

BLeB
  • 1,716
  • 17
  • 24
0

As a rule, I abhor one-line ifs except in this Perl case

operation if condition;
Paul Nathan
  • 39,638
  • 28
  • 112
  • 212
0

I have auto-format setup to kill your one-liner, which puts it on two lines. As such, it needs braces.

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
  • I'm curious why so many people are replying with irrelevant answers. Again, the question is about *how* to form one-liners, not *if he should*. – Adam Robinson Sep 16 '09 at 18:54
  • It's not irrelevant. There IS no one-line in my format-controlled source repository. It simply cannot exist, and therefore worrying about the problem is irrelevant. – Stefan Kendall Sep 16 '09 at 19:11
  • 1
    Furthermore, the OP asked preference. I gave mine. It's your COMMENT that's irrelevant, as you clearly didn't read the question. – Stefan Kendall Sep 16 '09 at 19:12
0

I always use enclosing brackets and I never code one line ifs, my approach looks like this

if(condition) { 
    statement = new assignment; 
}

because I code Java and that's the convention for the language. Check:

http://java.sun.com/docs/codeconv/html/CodeConventions.doc6.html#449

Note: if statements always use braces {}. Avoid the following error-prone form:

if (condition) //AVOID! THIS OMITS THE BRACES {}!
    statement;

The use of brackets prevent bugs: some else could add later new sentences that are suposed to be executed if the condition and forgetting the brackets

JuanZe
  • 8,007
  • 44
  • 58