473,396 Members | 1,799 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Coding standards and the ternary conditional operator

In his paper on Coding Standard found on

http://www.idesign.net/idesign/DesktopDefault.aspx

Juval Lowy discourages the use of the ternary conditional operator with no
specific reason given.

I can understand that complicated code would be much less readable using nested
operators, but aside from that is there another reason? -- something going on
under the hood perhaps which make it inadvisable to use?

Which one is better?

if(person != null)
{
return person.FirstName;
}
return null;

OR

return person != null ? person.FirstName : null;

Robert Zurer

Nov 17 '05 #1
6 2968
KH
There's nothing different under the hood. Some people suggest/prefer not
using the ternary op because it's meaning isn't that obvious, and it's
specific to the C-style languages (although I'm sure there's other languages
that have similar that I don't know about). Anyways I don't think there's
anything wrong with using it in simple cases like you show, but ugly, nested,
long usages get pretty messy pretty quick making code hard to read, maintain,
understand, etc.

One minor note on your example; some people suggest that a function should
have only one exit point, and I generally agree for finctions longer than a
couple lines. So, your if/else example might become:

object rv = null; // return value

if (person != null)
{
rv = person.FirstName;
}

return rv;

"Robert Zurer" wrote:
In his paper on Coding Standard found on

http://www.idesign.net/idesign/DesktopDefault.aspx

Juval Lowy discourages the use of the ternary conditional operator with no
specific reason given.

I can understand that complicated code would be much less readable using nested
operators, but aside from that is there another reason? -- something going on
under the hood perhaps which make it inadvisable to use?

Which one is better?

if(person != null)
{
return person.FirstName;
}
return null;

OR

return person != null ? person.FirstName : null;

Robert Zurer

Nov 17 '05 #2
Robert Zurer wrote:
Juval Lowy discourages the use of the ternary conditional operator with no
specific reason given.
He's not a fan of explanations. "Do it my way, whether you understand
it or not."
I can understand that complicated code would be much less readable using nested
operators, but aside from that is there another reason? -- something going on
under the hood perhaps which make it inadvisable to use?
No. It's just the same old "it can be abused, so it should be banned"
logic.
Which one is better?

if(person != null)
{
return person.FirstName;
}
return null;

OR

return person != null ? person.FirstName : null;


The second one, imho, makes it clear that we are returning a value,
here, and that that value depends on the state of the person
reference.

The first one - without even an "else" clause - makes the link between
"person == null" and "return null" much weaker and more indirect. It
takes a bit more thought to see the link, and it would be a bit easier
for careless maintenance to break the link entirely.

Imho, the ternary operator is just fine on the right hand side of an
assignment, or a return, or in a parameter expression.

It's not fine when a ternary operator is nested inside a larger
expression, with the POSSIBLE exception of something like

ThisString + (Counter != 1 ? "s" : "") + ThatString

--

www.midnightbeach.com
Nov 17 '05 #3
One minor note on your example; some people suggest that a function should
have only one exit point, and I generally agree for finctions longer than a
couple lines. So, your if/else example might become:

object rv = null; // return value

if (person != null)
{
rv = person.FirstName;
}

return rv;

Thanks for your response. It confirms what I thought. With regard to the single
exit point, is this also for readabilty, or is there another reason?

Recently I have started to use the multiple exit point style because it does
away with having to read through a lot of conditional logic which won't get
called.

Robert Zurer
Nov 17 '05 #4
The ternary operator is very handy.
I use it quite a lot in my work, which involves low level programming
microcontrollers in C. Before I was used to seing it, its meaning was
not immediately obvious to me. but now, I am quite happy to use it.

I think once you are used to using it, its meaning becomes quite
obvious. As has been said though, keep it simple, don't starting
nesting one inside another. I think that if you can't keep it all on
one line, it may be an idea to use if/else instead

Kevin R
Nov 17 '05 #5
Jon Shemitz wrote:
The first one - without even an "else" clause - makes the link between
"person == null" and "return null" much weaker and more indirect. It
takes a bit more thought to see the link, and it would be a bit easier
for careless maintenance to break the link entirely.


No Problem. Just rewrite it:

if(person == null)
{
return null;
}
return person.FirstName;

Which makes the link you discuss far clearly that either fragments in the
OP.
--
Truth,
James Curran [erstwhile-MVP]
Home: www.noveltheory.com Work: www.njtheater.com
Blog: www.honestillusion.com Day Job: www.partsearch.com
Nov 17 '05 #6
Single exit points are a (misguided) attempt to keep method logic simpler.
It is a good example of "throwing out the baby with the bathwater".

Sometimes, multiple exit points make a method clearer, and sometimes they
make it hard to follow or easy to overlook alternate conditions. I don't
hesitate to use them, say, in a simple method that just needs to return a
value based on a switch statement, e.g.,

private string Fooness(string foo) {

switch (foo) {
case "bar":
return "WasBar";
case "foo":
return "WasFoo";
default:
return null;
}

}

It's perfectly self-evident what this is doing, more so (and probably more
efficiently) than artificially creating a return variable, setting that
variable in the switch, and then doing a return of the variable at the end
of the method.

I suppose you could argue that methods tend to grow in complexity over time
and then you could end up with 20 cases, some of them rather large, and then
the returns would be "buried" in all the "noise", and therefore, this is a
bad practice. However, in that case, you should generally refactor this
back down to a short, sweet, simple method anyway, and call other methods to
handle lengthy cases.

I tend to favor "single exit point" designs only when they simplify /
clarify the intent of the code.

--Bob

"Robert Zurer" <ro**********@zurer.com> wrote in message
news:MP************************@news.microsoft.com ...
One minor note on your example; some people suggest that a function
should
have only one exit point, and I generally agree for finctions longer than
a
couple lines. So, your if/else example might become:

object rv = null; // return value

if (person != null)
{
rv = person.FirstName;
}

return rv;

Thanks for your response. It confirms what I thought. With regard to the
single
exit point, is this also for readabilty, or is there another reason?

Recently I have started to use the multiple exit point style because it
does
away with having to read through a lot of conditional logic which won't
get
called.

Robert Zurer

Nov 17 '05 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
by: Paul E Johnson | last post by:
Dear friends in C: I'm completely baffled by this problem I have with printf statements and conditional operators in C. I'm using gcc-3.3. I have a project where the rarely used Union type...
6
by: glongword | last post by:
As the assert macro should evaluate to a void expression, it should not have an 'if statement' in its definition. Does this necessitate the existence of a ternary conditional operator? Is there a...
144
by: Natt Serrasalmus | last post by:
After years of operating without any coding standards whatsoever, the company that I recently started working for has decided that it might be a good idea to have some. I'm involved in this...
48
by: Daniel Crespo | last post by:
Hi! I would like to know how can I do the PHP ternary operator/statement (... ? ... : ...) in Python... I want to something like: a = {'Huge': (quantity>90) ? True : False} Any...
5
by: slashdotcommacolon | last post by:
Hello, I've been asked to port some old code to a new platform. We have a vendor-supplied compiler that is supposed to be ansi compliant, but it refuses to compile the following code: $ cat...
3
by: Ben Wilson | last post by:
I read somewhere else that Python was getting a ternary operator (e.g. x = (true/false) ? y : z). I read the PEP about it and that the PEP had been approved this past Fall. Has this been released...
20
by: Udo A. Steinberg | last post by:
Hi all, In a ternary statement such as: x = (cond ? a : b); it is obviously guaranteed that "x" will be equal to "a" only if the condition "cond" holds. Assuming that "a" is a memory location,...
19
by: auratius | last post by:
http://www.auratius.co.za/CSharpCodingStandards.html Complete CSharp Coding Standards 1. Naming Conventions and Styles 2. Coding Practices 3. Project Settings and Project Structure 4....
4
by: raiderdav | last post by:
I understand how the ternary operator (question mark - ?) works in an if/else setting, but what does it mean when used as a type? For instance, I'm trying to add a get/set in some existing code,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.