aspose file tools*
The moose likes Beginning Java and the fly likes Best style for ternary operator in return statement Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Best style for ternary operator in return statement" Watch "Best style for ternary operator in return statement" New topic
Author

Best style for ternary operator in return statement

Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

I have a simple question/survey on coding style when using the ternary operator for a method's return. Which do people consider to be better style, and why? This came up in a discussion and I�m curious what others think.



Thanks in advance.

p.s. I'd love to know Peter's opinion this...
[ September 30, 2004: Message edited by: Mark Vedder ]
Peter van der Linden
author
Ranch Hand

Joined: Sep 28, 2004
Posts: 46
Hi Mark,

Excellent question!

It's always good to get some debate with other programmers about "is it better this way,
or that way" - and most programmers learn to listen in the end to what their colleagues
suggest. If they don't listen, it is going to take them much longer to grow as professionals.

I have to confess that I have never liked the "?:" ternary expression in either C or Java! I think
it is because I have seen too many places where it is abused - nesting it inside other
ternaries and so on. It quickly gets hard to read.

I had an excellent experience once where a (genuinely gifted) programmer brought me a
piece of code and told me that it wasn't working right, and was there a compiler bug. I
looked at the code. It was only 3 or so lines, but it was crammed with nested ternaries that
made it hard to read. I started using an editor to expand it into something more readable,
and the programmer jeered at me for being a wuss who didn't want to cope with the tough
expressions.

But his jeers quickly turned to chagrinned silence when I unpacked one line into the equivalent
but longer and more readable code, and it was immediately obvious to both of us that was
where his bug was! I have never forgotten that "Aha!" moment, and neither has he.

---

However, your statements aren't nested or unduly complex, or an inappropriate use
of the ternary expression.

I guess some people will say that a comparison with no negative is slightly simpler.
So they will prefer:


Other people will have their reasons for prefering


Me, I would personally write it like this:


I like that because it jumps out at you how you always return a value.
Just that if you didn't get a value by the time you get here, you give it the default.
Not a big deal; I would not flag it in a code review. All 3 alternatives seem good to me.

Insert all the standard remarks about following house style etc etc.

Would be interested to hear what others think.
Cheers,

Peter


Author of <a href="http://www.amazon.com/exec/obidos/ASIN/0131482114/ref=jranch-20" target="_blank" rel="nofollow">Just Java(TM) 2 (6th Edition)</a>
Francis Siu
Ranch Hand

Joined: Jan 04, 2003
Posts: 867
Peter answered the best way as a good programmer requires to do that.
coding style
It is a style that just you like and express an art of programming
One of my high school teacher told me that as you can do it, show out your program in one line. Because the program is for myself only, and it will not expose to other's.

Just want to share a joke in my way of learning
[ September 30, 2004: Message edited by: siu chung man ]

Francis Siu
SCJP, MCDBA
Pradeep bhatt
Ranch Hand

Joined: Feb 27, 2002
Posts: 8898

I like Peter's style of coding. It is easier to read.


Groovy
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Originally posted by Pradeep Bhat:
I like Peter's style of coding. It is easier to read.


I guess you are referring to the if-construct? Why do you find it easier to read?

To me, it uses up more brain cycles to understand it's intend:



- we want to do something when value is null
- we assign it a new value in that case, namely a default value
- and then we return value
- which is the original value when it wasn't null
- so we return the default value when the original one was null, the original one otherwise
- didn't I miss something? let's check again - ok, looks right



- we want to return something
- based on wether value != null
- value if it is
- a default value if it isn't

Actually I can get a sense of what's happening in the latter case by just skimming over it, for the former I actually have to read and analyze the code.


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
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60057
    
  65

I'm with Ilja on this one. I heartily agree with Peter that the ? operator is best used in simple cases that do not impair the clarity of the code. I think this is one of those cases, and find the single-line version more readable than the if construct.

But it's a minor point. And Peter's advice to follow "house rules", if any, are certainly valid.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

Hi Peter,

Thanks for the reply. Once upon a time, I was not a fan of the ternary expression and never used them. Recently I started to use them for very simple operations like the one demonstrated here. I think as soon as any of the conditions/expressions move beyond simple variables and become actual expressions (no matter how simple those expressions are), the ternary expression starts to get cloudy and muddy, and thus very difficult to read/decipher. Therefore, I personally would not use a ternary for anything more complex.

As I've read through code, I found the use of a simple ternary expression in a return statement to be understandable and acceptable, for reasons similar to what Ilja gives. Thus I have started to use them from time to time; mostly for this exact situation, a null check in a return statement. The discussion then came up as to whether in such a null check, do you want to check if the variable is null, or not null... which led to my question about preferred format.

As for nested ternaries, I agree they add unnecessary obfuscation to code. I think that anyone that uses them should be sent to the programmer�s dungeon for a lifetime sentence of dull drum code maintenance - maybe converting all String concatenations to use StringBuffers for a very large enterprise applications (and they wouldn�t be allowed to use search)

Regards,
Mark
Mark Vedder
Ranch Hand

Joined: Dec 17, 2003
Posts: 624

Originally posted by Bear Bibeault:
I'm with Ilja on this one. I heartily agree with Peter that the ? operator is best used in simple cases that do not impair the clarity of the code. I think this is one of those cases, and find the single-line version more readable than the if construct.

But it's a minor point. And Peter's advice to follow "house rules", if any, are certainly valid.


Bear,

Aside form the ternary vs. if statement discussion, for a ternary expression, which, if any, do you think is a cleaner format? Checking for null or check for not null?

What do others think?

-Mark

p.s. I agree, house rules should always apply. I'm currently in a small shop and our rules do not get that specific; something that is on the list of things to address "someday"...
Nigel Browne
Ranch Hand

Joined: May 15, 2001
Posts: 673
Personally I would check for null, but I feel it is a matter of taste and consistency. If you check for null in one place, it should be continued throughout the code so as to avoid code littered with both null and not null tests.
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60057
    
  65

which, if any, do you think is a cleaner format? Checking for null or check for not null?


I would use whichever makes the most sense in the context of its usage. If it's 50/50, I think that I usually check for the positive case (check for null).
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
As Peter, I feel that the negation makes it a tiny bit harder to read. On the other hand, I'd also like to have the normal case come first, the default come second.

I don't think the difference is significant, though - I'm certainly not consistent in this case
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Best style for ternary operator in return statement
 
Similar Threads
From 60 lines to 1 line?
how return value is resolved
Alternative to if else block
can any one explain this
<f:param using ternary operator problem