File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes a question on If else statement. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "a question on If else statement." Watch "a question on If else statement." New topic
Author

a question on If else statement.

Yan Hu
Greenhorn

Joined: Sep 07, 2004
Posts: 19
Hi there:

Here is a method that uses an ifelse statement.

public String doSomething(String param){
if(conditionA){
do some work here
return string_a
}
else{
do some work here
return string_b
}

}

Someone said that the logic here is a bit sloppy since the second return doesn't make sense even if the compiler will not complain about it.

Why is it sloppy? Should I just make it

public String doSomething(String param){
if(conditionA){
do some work here;
return string_a;
}

do some work here
return string_b;
}

Why is the second one better than the 1st one? If not, what seems to be not sloppy? Thank you very much for your time.


Programming is an art<br />Yan Hu
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

The second one is not better than the first one -- I think the first one is better. The structure of the first one makes it clear that only one of the paths can execute; the second form you have to read and understand the code to see that.

Occasionally -- too often, in fact -- you'll meet a programmer who thinks that the fewer characters you type, the better the code is. I think the person who told you #2 was better is one of those people. Don't listen to that kind of advice -- clear code is much better than short code, always!


[Jess in Action][AskingGoodQuestions]
peter greaves
Ranch Hand

Joined: Sep 27, 2002
Posts: 51
some code purists might prefer:



on the basis that one return statement in a method makes the method's exit point easy to find. matter of style i guess.
[ September 30, 2004: Message edited by: peter greaves ]

SJCP 1.2
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392

on the basis that one return statement in a method makes the method's exit point easy to find. matter of style i guess.


JavaRanch's style guide advocates this approach.

Joyce
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Originally posted by Joyce Lee:
JavaRanch's style guide advocates this approach.


This is but one of many aspects of the JR style guide that are controversial topics even among the staff. I think -- and I've got lots of people on my side, including Steve McConnell, author of "Code Complete" -- that the "one exit" rule is an outdated relic: the guiding principle should always be clarity, not blindly following a strict rule.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Joyce Lee:


JavaRanch's style guide advocates this approach.



And personally I think it's rubbish...

Seriously, I know of three reasons to only have one return statement:

- Academics often say that it's easier to reason about methods with only one exit point. That's probably true if you want to apply mathematic proves; as I prefer other means to check the correctness of my code, it doesn't apply to me.

- Some people say that more than one exit point makes it harder to understand a method. In my experience this only true for big methods - for methods of the size I prefer (not more than a handfull of lines), I find that early returns actually can improve readability.

- Early returns can make it harder to refactor the code - the typical refactoring browser won't allow you to extract code with multiple returns into it's own method. That's a valid concern to me, although readability still trumphs it.

Most often I use early returns for Guard Clauses: http://c2.com/cgi/wiki?GuardClause


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
Besides this, what other aspects of the JR style guide that are controversial? Is there any plan to update the style guide?

that the "one exit" rule is an outdated relic: the guiding principle should always be clarity, not blindly following a strict rule.
Ernest, I agree that clarity should be the guiding principle. But how can we follow this principle among the co-workers when readability is so subjective?

Joyce
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

Originally posted by Joyce Lee:
[H]ow can we follow this principle among the co-workers when readability is so subjective?


I don't have a short answer for this. Reading (there have been many writers on this topic) and practice are important. Pair programming, with frequent partner-switching, helps a lot too.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
If you allow multiple returns in your particular style ...

is nicely symmetrical for such a short fragment. But

Really bugs me. "do that" and "do more" are in separate blocks, but they always occur together for exactly the same reason. I'd lose the "else" in that case. Maybe it's just me but "else" after "return" is usually ugly.


A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Warren Dew
blacksmith
Ranch Hand

Joined: Mar 04, 2004
Posts: 1332
    
    2
Ilja Preuss:

- Some people say that more than one exit point makes it harder to understand a method. In my experience this only true for big methods - for methods of the size I prefer (not more than a handfull of lines), I find that early returns actually can improve readability.

I feel that early returns almost always make a function easier to understand, regardless of the size. Once you understand the code path that leads to the early return, you can forget about it and read on. If the early return is missing, you have to try to keep that code path in mind while reading the rest of the function, which is more difficult.

I think "one exit point" became obsolete at the same time as the goto statement.
Stefan Wagner
Ranch Hand

Joined: Jun 02, 2003
Posts: 1923

I prefer early returns too.
If the result is clear - return it and finito.

Else you need not only the else, but a result-variable too.
But - as mentioned by Warren, it's easier to understand.

It might lead to lean switch-statements too:

compared to:
[ September 30, 2004: Message edited by: Stefan Wagner ]

http://home.arcor.de/hirnstrom/bewerbung
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Warren Dew:
If the early return is missing, you have to try to keep that code path in mind while reading the rest of the function, which is more difficult.


True. On the other hand if you are mainly interested in something near the end of the method, it can become hard to see under which circumstances it will be executed.
Peter Chase
Ranch Hand

Joined: Oct 30, 2001
Posts: 1970

[/qb]<hr></blockquote>

If you do like this style (and I'm not sure), I think it is a good idea not to initialise "result" to anything, even null. The reason is that not initialising it allows the Java compiler to detect an execution path in which "result" has not been set, which is a fatal error in Java compilation (c.f. 'C', where it is at best a warning). Initialising to null, when you never actually intend to return null, is defeating the compilers ability to help you here.
[ October 01, 2004: Message edited by: Peter Chase ]

Betty Rubble? Well, I would go with Betty... but I'd be thinking of Wilma.
peter greaves
Ranch Hand

Joined: Sep 27, 2002
Posts: 51
thanks for that note re: the compiler and nulls, peter. interesting.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Originally posted by Ilja Preuss:

True. On the other hand if you are mainly interested in something near the end of the method, it can become hard to see under which circumstances it will be executed.


Wait ... I know you and I don't write methods long enough to forget the beginning by the time you read to the end!
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Stan James:
Wait ... I know you and I don't write methods long enough to forget the beginning by the time you read to the end!


But I was replying to "I feel that early returns almost always make a function easier to understand, regardless of the size."
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Joyce]: Besides this, what other aspects of the JR style guide that are controversial? Is there any plan to update the style guide?

The guide gets updated periodically for clarity. It almost never changes as far as the actual (intended) rules are concerned; the original author is too set in his ways.

The main areas where some of us disagree are:
  • Required spacing around identifiers
  • Brace style
  • Naming of constants
  • Capitalization of acronyms
  • Private helper methods before public methods that use them
  • Required braces after if/else/for/while
  • All the "Never use..." stuff in 3.1 (to varying degrees)
  • "95% of the standards outlined in this document are what is found in the JDK source" - yeah, right
  • "Try to always initialize all variables when they are declared"

  • The level of disagreement on each of these varies. In some cases only one or two people disagree; in one case I don't think anyone agrees with Paul. (If anyone else thinks required space around identifiers (always) is a good idea, I haven't seen it.) That's not to say that we have strong objections to the style guide - just that if we were all writing guides of our own, many of us would write different rules than what's in the Coop guide.

    Here is a sampling of some of the past discussions we've had, mostly about the braces issue (which developers will never fully agree on anyway):

    [link] [link] [link] [link] [link]
    [ October 02, 2004: Message edited by: Jim Yingst ]

    "I'm not back." - Bill Harding, Twister
    Warren Dew
    blacksmith
    Ranch Hand

    Joined: Mar 04, 2004
    Posts: 1332
        
        2
    Jim, to bring up another point of contention, I think your post is a good argument for line length limits.
    Jim Yingst
    Wanderer
    Sheriff

    Joined: Jan 30, 2000
    Posts: 18671
    Agreed. Well, I fixed it now. Thanks.
    Joyce Lee
    Ranch Hand

    Joined: Jul 11, 2003
    Posts: 1392
    Many thanks, Jim!

    As you know, I'm a student of Cattle Drive, so it doesn't matter whether if I agree or disagree with the styles while doing the assigments. But when writing code other than the Cattle Drive assignments, I'll switch back to Sun's styles. The reason why I prefer Sun's style because it's common and it's consistent with the Sun documentation/API. It requires some mental effort when switching between the two coding conventions like the spacing, naming of constant, capitalization of acronym, etc. The brace style is ok for me (I can switch without effort). I actually prefer having braces after if/else/for/while for single statement, it's clearer.


    "95% of the standards outlined in this document are what is found in the JDK source" - yeah, right



    I saw this blog and I agree with Bruce Eckel's advice.

    Joyce
    [ October 03, 2004: Message edited by: Joyce Lee ]
    Ilja Preuss
    author
    Sheriff

    Joined: Jul 11, 2001
    Posts: 14112
    Originally posted by Jim Yingst:
    That's not to say that we have strong objections to the style guide - just that if we were all writing guides of our own, many of us would write different rules than what's in the Coop guide.


    Yes - and there is nothing wrong with it.

    In my opinion, there are only three important rules a style guide should follow:

    - you have one (doesn't even need to be written down),
    - the whole team agrees to follow it, and
    - it really is only about style
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: a question on If else statement.