if statement

C

charles_n_may

One benefit the ternary operator offers over the if-else is the ability
to declare the result "final" in one line:

final int borderAge = isMale ? 65 : 60;

If you do it this way, you have compiler-checks to ensure your code
doesn't change the value of borderAge within the current scope. If you
want to achieve a final result using an if-then, you have to leave a
temporary variable dangling in order to do it, and the result is
messier:

int temp;
if (isMale) {
temp=65;
} else {
temp=60;
}
final int borderAge = temp;
 
C

Chris Uppal

Monique said:
Objectively, I think you're wrong. I really mean that I think the
if/else syntax is clearer

You've got to be a bit careful here. There are (at least) two aspects to
clarity. One is how well does the programming construct capture the intent of
the programmer, the other is how clearly is that construct expressed in the
concrete syntax of the language.

In this case I think these two aspects work in different directions.

First off, if the concept is something like (for instance):

if the person is female then the retirement age is 60, otherwise
it's 65.

Note two things about that: (1) we are covering /all/ the possibilities (2) we
are using the two values (60 and 65) for the same purpose (as signified by the
fact that we don't -- and in normal English shouldn't -- repeat the phrase
"retirement age").

Now we can translate that concept into Java code using an if statement:

if (person.isFemale())
retirementAge = 60;
else
retirementAge = 65;

but that doesn't capture the concept particularly well. There is nothing to
stop us missing off the else (either syntactically or logically); and there is
nothing to hint that the important thing is that the same variable,
retirementAge, is assigned on both branches. So the notation is an /indirect/
expression of our intent. It works, but it's not as clear as it should be.

Using an ?: operator, OTOH, is a very direct expression of our intention:

retirementAge = person.isFemale()
? 60
: 65;

The reader doesn't have to /notice/ that the same variable is assigned to in
each case -- there is only one assignment. Similarly there is no possibility
of forgetting to cover the cases.

So, as far as that goes, the ?: operator (if used correctly) is significantly,
and objectively, clearer than an if statement.

But that's only half the story. /Given/ that a conditional expression is to be
preferred over conditional execution of different statements, does Java's
concrete syntax convey the underlying semantics well ? Now there, I agree, the
answer is an objective "no". It's something that you just have to get used to.
It belongs in the long tradition of punctuation abuse, which has been a central
feature of programming language design, more-or-less from the very beginning.

The syntactic unclarity is something that you /can/ get used to (especially if
you use decent layout conventions), and with experience you find the syntax
more and more transparent. But the unclarity in the other department is
inherent -- it's not something that goes away as you get used to it. If
anything it's the other way around -- as your sensitivity develops you find it
more and more off-putting.

-- chris
 
T

Thomas Hawtin

One benefit the ternary operator offers over the if-else is the ability
to declare the result "final" in one line:

final int borderAge = isMale ? 65 : 60;

If you do it this way, you have compiler-checks to ensure your code
doesn't change the value of borderAge within the current scope. If you
want to achieve a final result using an if-then, you have to leave a
temporary variable dangling in order to do it, and the result is
messier:

int temp;
if (isMale) {
temp=65;
} else {
temp=60;
}
final int borderAge = temp;

Not true. Go read the chapter on definite assignment.

Tom Hawtin
 
G

Gordon Beaton

What I was getting at is that short circuiting happens rarely (I
believe it only happens for the ?:, || and && operators), and so a
beginning programmer might (wrongly) assume that it does not happen
for the ternary operator.

As such, the programmer might expect all three expressions to get
evaluated. If the intention truly was to ensure that everything gets
evaluated, it might have been clearer to write the code as:

The only time it's important to evaluate every component of a compound
expression is when those components are not side-effect free. And if
that's the case, your expression is more correctly called a statement,
in which case if-else (i.e. the conditional statement) is an
appropriate choice.

If your expressions have no side-effects (i.e. only their values are
important), then I see no reason not to choose the conditional
operator (aka ternary operator) to produce a compound expression.

I don't see what all the fuss is about.

/gordon
 
G

Gordon Beaton

People can go on "objectively" about how ternary is better than if/else,
if/else is better than ternary, whatever. I personally find if/else
clearer, but I find the elaborate justifications for each person's point
of view on the matter to be entertaining, in much the same way as I
prefer vi but still find vi/emacs debates amusing and bemusing.

Neither is "better" in the general case, however they are semantically
different. if-else is for creating conditional statements, while ?: is
for creating conditional expressions.

/gordon
 
O

Oliver Wong

Thomas G. Marshall said:
Oliver Wong coughed up: [snip]
Also, Java does some short circuiting with the ternary operator, so
that:

int borderAge = isMale ? getMaleBorderAge() : getFemaleBorderAge();

will only result in one method call,

*Same* as with the if/else.

which may or may not be the
intention of the programmer (this is important if the methods have some
sort
of side effect). Rewriting this as an if-else-statement usually makes the
intent explicit.

Huh? Explicit how? The if/else *might* have been arranged differently,
but then, so might the code containing the ?: ternary.

What I was getting at is that short circuiting happens rarely (I believe
it only happens for the ?:, || and && operators), and so a beginning
programmer might (wrongly) assume that it does not happen for the ternary
operator.

As such, the programmer might expect all three expressions to get
evaluated. If the intention truly was to ensure that everything gets
evaluated, it might have been clearer to write the code as:

<code>
int result1 = getMaleBorderAge();
int result2 = getFemaleBorderAge();
if (isMale) {
int borderAge = result1;
} else {
int borderAge = result1;
}
</code>

In other words, I think a higher percentage of Java programmers will
correctly determine what this code does:

<code>
int borderAge;
if (isMale) {
borderAge = getMaleBorderAge();
} else {
borderAge = getFemaleBorderAge();
}
</code>

than this code:

<code>
int borderAge = isMale ? getMaleBorderAge() : getFemaleBorderAge();
</code>

- Oliver
 
O

Oliver Wong

One benefit the ternary operator offers over the if-else is the ability
to declare the result "final" in one line:

final int borderAge = isMale ? 65 : 60;

If you do it this way, you have compiler-checks to ensure your code
doesn't change the value of borderAge within the current scope. If you
want to achieve a final result using an if-then, you have to leave a
temporary variable dangling in order to do it, and the result is
messier:

int temp;
if (isMale) {
temp=65;
} else {
temp=60;
}
final int borderAge = temp;

You can write this:

final int borderAge;
if (isMale) {
borderAge = 65;
} else {
borderAge = 60;
}

- Oliver
 
C

charles_n_may

I stand corrected. I must have had this in my mind from a previous
experience where the else was omitted. Thanks for the reference.

For what it's worth, I prefer the ternary expression when it is not
overly verbose.
 
M

Monique Y. Mudama

Roedy Green coughed up:
This is elegant. Every fact is specified only once with the
absolute minimum of clutter.

Perhaps having a way to speak it internally to yourself might help
you appreciate it.

REREAD what I wrote. I advocate the :? !!!

...[misdirected examples snipped]...

Read Roedy's attribution line.

(Personally I think that attribution line is just an attempt to
justify laziness in proper snipping, but that's just me.)
 
O

Oliver Wong

J. Verdrengh said:
Ok, but this definition is subjective: depending on the person using it,
the outcome may be different. Thus it can't be used for absolute decisions
about which form is clearer.

Agreed. I was surprised when Roedy opened his post with "Objectively,
this is clearer" (Less surprised when Monique and Thomas used it, as I
assume it was to point out the absurdity of describing the clarity as being
objective in the posts they were responding to).

This is just my opinion, but I think people are allowed to form judges
about what is or isn't clear even if they haven't had training on the
subject matter. In fact, perhaps as a "true" test that a concept is a clear,
we can see if people who have NOT been trained are able to grasp the
concept. If so, then that concept must be extremely clear.

If we agree to this definition (and I'm not saying we have, this is just
a theoretical situation here), then I think, objectively, most English
speakers will find the "if-else" form clearer than the ternary operator.

That is, even non-programmers can guess what will happen with respect to
the "if-else" form; that's an indication of how clear it is.

Of course, Chris Uppal made an extremely good argument (in my opinion)
for the clarity of the ternary operator; namely that it makes it clear that
the same variable is being assigned to in both branches of the condition.

So, like so many things, it all depends on your definition of "clear"
(as Verdrengh pointed out).

- Oliver.
 
M

Monique Y. Mudama

I stand corrected. I must have had this in my mind from a previous
experience where the else was omitted. Thanks for the reference.

For what it's worth, I prefer the ternary expression when it is not
overly verbose.

I think the subjectiveness of your last sentence (overly verbose is in
the eye of the beholder) just goes to show that this entire argument
is about a matter of stylistic preference.

People can go on "objectively" about how ternary is better than if/else,
if/else is better than ternary, whatever. I personally find if/else
clearer, but I find the elaborate justifications for each person's point
of view on the matter to be entertaining, in much the same way as I
prefer vi but still find vi/emacs debates amusing and bemusing.
 
M

Monique Y. Mudama

Agreed. I was surprised when Roedy opened his post with
"Objectively, this is clearer" (Less surprised when Monique and
Thomas used it, as I assume it was to point out the absurdity of
describing the clarity as being objective in the posts they were
responding to).

That's certainly what I meant to convey =)
 
R

Roedy Green

But I conjecture that it won't be. The brevity will win out. The
problem is people are making up their minds before they are
comfortable with both syntaxes.

My definition allows an objective experiment to settle the question.
You could conceivably find that in a population of 100 programmers not
all 100 will go the same way but you can objectively measure each
programmer's ability to accurately determine the meaning of code
presented either way.

It is not just a matter of which you like.
 
M

Monique Y. Mudama

But I conjecture that it won't be. The brevity will win out. The
problem is people are making up their minds before they are
comfortable with both syntaxes.

My definition allows an objective experiment to settle the
question. You could conceivably find that in a population of 100
programmers not all 100 will go the same way but you can objectively
measure each programmer's ability to accurately determine the
meaning of code presented either way.

It is not just a matter of which you like.

Okay, you really need to stop with this business of snipping out all
attribution and then lamely "covering" yourself with an attribution
line that acknowledges as much. It's completely impossible to figure
out who said what when replying to you.

Trimming is not that hard.

I am still trying to figure out how you can pull these kinds of
arguments about definitions when you killfiled someone (not to mention
a lot of verbal, er, typed, abuse) for supposedly being a language
lawyer. Pot, kettle?

I have lost track of the discussion, but I am having trouble imagining
a situation in which a coder would understand a well-formatted example
of the ternary operator, then read the same thing in if/else format
and be uncertain. I can certainly imagine the reverse situation.
 
S

Stefan Ram

Chris Uppal said:
retirementAge = person.isFemale()
? 60
: 65;

Another possibility might be:

retirementAge = person.ifFemale( 60, 65 );

The drawback is the evaluation of both arguments, which here
is not so disturbing in the special case of "( 60, 65 )".

This "ifFemale" solution follows the guideline "Don't ask
objects for information and do it yourself, but ask the object
that holds the information needed, to do it for you
(delegate)." (in this case: to do the selection of a value.)

Now, just for fun, how to avoid both arguments (i.e., "60" and
"65") being evaluated?

retirementAge = person.ifFemale
( new java.util.concurrent.Callable<int>(){ public int call(){ return 60; }},
new java.util.concurrent.Callable<int>(){ public int call(){ return 65; }});

(not tested.)
 
O

Oliver Wong

Stefan Ram said:
Now, just for fun, how to avoid both arguments (i.e., "60" and
"65") being evaluated?

retirementAge = person.ifFemale
( new java.util.concurrent.Callable<int>(){ public int call(){ return
60; }},
new java.util.concurrent.Callable<int>(){ public int call(){ return
65; }});

(not tested.)

Objectively, I vote for this as the implemention which most closely
reflects the original intention, and hence the clearest.

- Oliver
 
S

Scott Ellsworth

Roedy Green said:
But I conjecture that it won't be. The brevity will win out. The
problem is people are making up their minds before they are
comfortable with both syntaxes.

I disagree with your claim that disliking ternary operators is driven by
making up one's mind before getting comfortable with the syntax.

I am quite familiar with ternary operators; I first saw them back in
'86, 19 years ago. I have been doing Java now for seven years, and did
C++ for eight years before that. (Yep. Cfront was my friend.)

I have gone back and forth over the years, but I find that I am settling
in a stable state of disliking ternary operators intensely, precisely
because the code I have written and maintained that used them seems
harder to maintain than code that uses plain old if statements.

I know quite a few others here with similar experience who feel much the
same. (And counterexamples, of course.) Thus, I suspect it really is a
preference based on how you chunk the data, and what you find
straightforward.

Scott
 
T

Thomas G. Marshall

Monique Y. Mudama coughed up:
I think the subjectiveness of your last sentence (overly verbose is in
the eye of the beholder) just goes to show that this entire argument
is about a matter of stylistic preference.

People can go on "objectively" about how ternary is better than if/else,
if/else is better than ternary, whatever. I personally find if/else
clearer, but I find the elaborate justifications for each person's point
of view on the matter to be entertaining, in much the same way as I
prefer vi but still find vi/emacs debates amusing and bemusing.


I prefer vi only because 1. I ran a small unix department where the machines
I had to port to often had nothing else, and 2. I was horrified by how just
plain /weird/ emaxs is.
 
M

Monique Y. Mudama

Objectively, I vote for this as the implemention which most closely
reflects the original intention, and hence the clearest.

- Oliver

If I had liquid in my mouth, you'd owe me a new monitor right now!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,020
Latest member
GenesisGai

Latest Threads

Top