• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • paul wheaton
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • Mikalai Zaikin
  • Himai Minh

An interesting point for if-else structure

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
We all know the standard if-else structure is like if -> else if -> else:



But I do have seen some codes without the ending else:



Seems it is actually equivalent to the three parallel if statements:



So is the no-ending-else structure is a bad coding practice? Does it matter to compilation speed since Java does not find the ending else?
 
Rancher
Posts: 3844
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm not sure why the formatting of this post is getting messed up... I didn't put in any < br > tags, and it loks fine in the editor before I submit.  But something happens after that.  Anyway...

Miles Jiang wrote:We all know the standard if-else structure is like if -> else if -> else:

<br /> Well no, I don't know that one.  The final "else" can't have any condition: <br /> <br /> I'm not sure what would make it a bad coding practice.  Well, people will be happier if you use braces around each "then" section.  But that's not what you're asking about. <br /> <br /> The compiler speed won't be an issue, really.  More relevant are readability, minimizing possible programmer error, and execution speed.   <br /> <br /> In a case like this, two things that jump out to me about the list of conditions are that it's  exclusive (we can't have  more than one condition true) and exhaustive (there must always be one true).  In such cases, I see no reason not to use a simple else for the last case, since there's nothing new to test.  If you've already tested for a > 0 and a < 0, the only remaining possibility (for int at least) is a == 0, no need to actually test it.  But some people may find it more readably to say it explicitly.  I would usually comment it: <br /> <br /> On the other hand, sometimes you may think you have an exhaustive list of the possibilities, but you don't.  If variable a had been a double, then it could possibly be NaN, not a number.  In which case a > 0, a < 0, a==0 are all false.  So it may be best to explicitly state the condition each time, just in case one of your assumptions is faulty.
 
Miles Jiang
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Good explanation, Mike. For braces, I strongly agree with you that curly braces be used after every while, do/while, if-else, for, and for-each structure, even if there is only one statement. Actually, according to coding guidelines from lots of companies, curly braces are required at all times. Except for taking the certification exam, always using curly braces would be a good idea as well as good practice, in my opinion.

For my original post, the fact is Java also accepts structures like if -> else if -> else if, instead of the standard if -> else if -> else only. But the "non-standard" structure should be avoided while writing code, I guess? Since nearly every programming textbook would teach you only the "standard" structure.
 
Marshal
Posts: 26523
81
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
There's really no such "standard" in Java. If your if-statement requires an else-clause, then write one. And if it doesn't require one, then don't write one.


There's no need for an else-clause here, for example, and in fact you shouldn't write one.

Now true, you're describing a situation where the if-statement is inside the else-clause of a different if-statement, but there's no reason why that if-statement should be treated any differently than any other if-statement. So that "standard" doesn't apply there either.

As for the curly braces: Yes, even when there's only one statement being delimited by them. Otherwise it's way too easy to add a second statement which you think belongs in the else-clause (let's say) with the statement which is already there, but it doesn't work that way. However for my personal coding I do make an exception: sometimes there's code at the beginning of a method to weed out situations where nothing needs to happen, so I do like this:


Note that it's all on one line, so the standard blunder of adding another line below that is unlikely to happen. And it's a return statement too. But if I worked in a place which insisted on the braces around the return statement there, I wouldn't complain about that.

(I thought that bug where <br> tags showed up sometimes had been fixed, but apparently not. If, when posting, you have a check-box which says "Disable HTML in this message" then checking it makes the bug go away.)
 
Miles Jiang
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks for clarification, Paul. Seems I got the point (correct me if I'm wrong):

1. else statement can't exist alone. If you see an else statement, there must be one (and only one) if statement somewhere before it.

2. if statement can exist alone.

3. So the if -> else if -> else if structure is effectively equivalent to (if-else) -> (if-else) -> if.
 
Paul Clapham
Marshal
Posts: 26523
81
Eclipse IDE Firefox Browser MySQL Database
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
1. Not really. When you see "else" you know it has to be associated with the "if" which precedes it structurally. What I mean is, the code between "if" and its associated "else" can contain anything -- including any number of if-clauses which may or may not have else-clauses, and they may in turn have nested code which in turn may contain anything, and so on.

2. Yes. Other languages make you say "then" before the code controlled by "if", so you'd have for example "if (a==0) then bla bla" or "if (a==0) then bla bla else yada yada", which could maybe be easier to read if you've got a lot of nested if's.

3. I wouldn't say that at all. But on the other hand the problem you're trying to address with this discussion isn't a problem at all for me, so I don't need explanations of that type. And it doesn't mean anything to me either. I'll just mention again that between "if" and its associated "else" there can be all kinds of code.
 
Miles Jiang
Greenhorn
Posts: 11
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Good recap. Thanks a lot!
 
Enthuware Software Support
Posts: 4540
45
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is an age old problem in programming languages.
https://en.wikipedia.org/wiki/Dangling_else

Specifically, for Java: https://stackoverflow.com/questions/32076762/java-statements-processing-precedence-dangling-else

Paul Clapham wrote:1. Not really. When you see "else" you know it has to be associated with the "if" which precedes it structurally.


That says it all.
 
Ranch Foreman
Posts: 347
8
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That was a weirder than average question.

Perl has a single keyword for that, spelled oddly:

elseif
The "else if" keyword is spelled elsif in Perl. There's no elif or else if either. It does parse elseif, but only to warn you about not using it.



Python doesn't provide switch case structures due to its interpreted nature.
It seems like an easy thing to add, but it is by no means easy.  I once read Guido's rationale why they didn't have it, and I wanted to stop but just kept on going.

So the else if kinda tree becomes even more important.
It looks like this:


Why does Perl spell it 'elsif' but Python spells it 'elif'?

Elif I know.
 
Miles Jiang
Greenhorn
Posts: 11
  • Likes 2
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

It is an age old problem in programming languages.
https://en.wikipedia.org/wiki/Dangling_else

Specifically, for Java: https://stackoverflow.com/questions/32076762/java-statements-processing-precedence-dangling-else



I guess this illustrates why using curly braces is always a good idea, especially for rookie developers.
 
Saloon Keeper
Posts: 23515
161
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Miles Jiang wrote:

It is an age old problem in programming languages.
https://en.wikipedia.org/wiki/Dangling_else

Specifically, for Java: https://stackoverflow.com/questions/32076762/java-statements-processing-precedence-dangling-else



I guess this illustrates why using curly braces is always a good idea, especially for rookie developers.



No, it's a highly-recommended idea for everybody.

A cannot tell you the number of times I've been zapped by an unbracketed conditional when I slipped in an extra statement just for debugging.

Aside from that, let me observe that one of my classic anti-bugging techniques is to assign a definite result to all conditionals. That is, instead of
I do this:
While you might consider this less efficient, the overhead would be rather small considering the peace of mind.  Plus these days, I'd expect that the compiler should optimize things.

Additionally, stacking "if" clauses like:
Is also an invitation to bugs. Sure, only one "if" is supposed to fire, but later maintainers can easily break that without even realizing it. Of course, where possible, a "select" statement is the better option, but not everything in a cascade of "if"s computers as a simple integer comparison and not all languages can handle "selects" for more complex constructs. So do the if/else if//else if/,.. thing.

And if you have a selectable stack of actions and you're working with "fuzzy" values (such as floating-point), then doing the pre-assignment I mentioned eatlier is even more important!
 
 
Mike Simmons
Rancher
Posts: 3844
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
To be fair, strict adherence to "always use curly braces" would mean that this:

should become this:

Now that seems a bit excessive; we generally agree on making an exception for else if:

While this is fairly standard Java style, I personally would like to make it more compact.  If we insist on always using braces (except of course for else if) then we could still do:

(I would note that the introduction of lambdas has made me much more tempted to put braces on the same line for short statements.)
Then too, I am a big fan of using ternary operators like this:

Which may be less "readable"  to people not used to seeing it.  But I find readability is often subjective, and based on what you are used to seeing.  I encourage people to expand their notion of readability to include chained ternary operators, mimicking the else if structure we already accept.
 
Tim Holloway
Saloon Keeper
Posts: 23515
161
Android Eclipse IDE Tomcat Server Redhat Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yeah, since Java doesn't have an "elseif/elif/elsif" construct, I do treat "else if" as an equivalent in terms of braces. I think in terms of logic levels more than of syntactic levels.

Arguments have been made for and against putting braces and brace bodies on the same line and there is much to be said for both sides. Certainly doing it all  on one line is more compact. Though using an independent line gives more emphasis to my eyes, so I usually go with that. My reasoning being that if it was important enough to be conditional, it's important enough to stand out.
 
Miles Jiang
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

(I would note that the introduction of lambdas has made me much more tempted to put braces on the same line for short statements.)
Then too, I am a big fan of using ternary operators like this:



Which may be less "readable"  to people not used to seeing it.  But I find readability is often subjective, and based on what you are used to seeing.  I encourage people to expand their notion of readability to include chained ternary operators, mimicking the else if structure we already accept.



To reduce the number of curly braces, some companies I know require to use of ternary operators instead of if-else statements for all simple conditionals, similar to the example Mike provided above. That is, the following if-else statement is even not accepted in certain companies any more.



To comply with the coding guideline, developers are required to use ternary operators whenever possible.



Another good practice, I guess?
 
Paul Clapham
Marshal
Posts: 26523
81
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I suppose it's not a bad practice. However let's suppose that you later have to change your code to be like this:



Then your clean-looking structure of ternary operators is broken and has to be rewritten as if-else again. Still, changes happen and sometimes a seemingly small change can require a larger-than-expected reorganization of your code, so I wouldn't fuss about that too much.
 
Mike Simmons
Rancher
Posts: 3844
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Miles, I tend to prefer that style.  Not sure I like it as a requirement.  But personally, I would probably make that change whenever I notice it's possible.

@Paul, yes that's a good counterexample.  But, it's also very possible that as those two if/else branches grow, they will move apart in ways where they shouldn't have, because of unnecessary code duplication that goes unnoticed by future maintainers.  Someone will fix a NullPointerException in one branch, not noticing that the same fix should be applied to the other branch as well... that sort of thing.  I prefer to minimize duplication in the first place (and/or minimize it later, when I notice it's possible) - if we need to expand it later because of changing requirements, we can.    
 
Marshal
Posts: 72612
317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike Simmons wrote:. . . Then too, I am a big fan of using ternary operators like this:

Which may be less "readable"  to people not used to seeing it. . . .

I like that construct, and the old Sun style guide recommends it too, but you can improve its legibility even more by adding a little space so the operators or operator parts align vertically:-I presume you meant to use >= throught rather than >? Surely D doesn't start at 61, or 60.000000000001? In which case I would reverse the whole statement structure:-I don't think there is a standard indentation convention for nested ?:s. Unfortunately ?: is one of those things beginners aren't made to use ugh, so they neer gain familiarity with it.

If you go through Cay Horstmann't books on paper, you find he has been putting {...} on one line for ages.
 
Campbell Ritchie
Marshal
Posts: 72612
317
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Miles Jiang wrote:We all know the standard if-else structure is like if -> else if -> else:

. . .

That looks strange. I don't think line 6 will compile; if it does, that code won't run correctly.
 
Mike Simmons
Rancher
Posts: 3844
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
@Campbell, yes the ">" were all supposed to be ">=";not sure how I overlooked that.

I like the idea of lining things up vertically like you show, and I used to do that.  But in practice, I found I was always fighting with automatic code reformatting.  I haven't seen a formatting tool that can tell the difference between extra spaces that someone put in accidentally, and those that were put there intentionally for aesthetic effect.  So I've generally abandoned such attempts.

Cay Horstmann's own style guide puts his style nicely: "Opening and closing braces must line up, either horizontally or vertically."  He also manages to not use any more lines than K&R style, letting the opening brace share a line with the next line... which is weird in its own way.  But I like the consistency and simplicity of "either vertically or horizontally"
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic