wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes If Statements Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "If Statements " Watch "If Statements " New topic
Author

If Statements

Jim Ball
Greenhorn

Joined: Dec 05, 2006
Posts: 8
I am wondering if using two if statements back-to-back is bad java coding practice. Below, is an example of when you might want to use the aforementioned if statement setup. Would a switch statement be a better way to go, or is the below type of coding design not a problem?

int x = 2; //Default value or else compiler might complain
if (x = 0){
do something;
}
if (x = 1){
do something else;
}
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60808
    
  65

In general, back to back ifs aren't necessarily any problem. But in the case you show -- in which the conditonals are the same execpt for a target value -- I would probably have opted for a switch.

It's "tidier" and there's less chance of transcription error as the variable x would be referenced once with the value being the only variable. This more closely matches the intention of your construct than the serial ifs would.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60808
    
  65

Oh, that all assumes that you meant:


[ December 07, 2006: Message edited by: Bear Bibeault ]
fred rosenberger
lowercase baba
Bartender

Joined: Oct 02, 2003
Posts: 11170
    
  16

of course, it's possible in this situation that the "do something" has a side effect of changing the value of x to 1, in which case the second if would ALSO run. Again, if that's what you want, you're fine.


There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Katrina Owen
Sheriff

Joined: Nov 03, 2006
Posts: 1357
    
  17
An alternative to the switch would be



The choices would then be mutually exclusive.
Neerav Narielwala
Ranch Hand

Joined: Dec 08, 2006
Posts: 106
yes you must use :
if()
{
}
else if()
{
}

It's a good programming practice...


<a href="http://www.java-tips.org/java-tutorials/tutorials/" target="_blank" rel="nofollow">Java Tutorials</a> | <a href="http://www.planet-java.org" target="_blank" rel="nofollow">Java Weblog</a> | <a href="http://computer-engineering.science-tips.org" target="_blank" rel="nofollow">Computing Articles</a>
M. Lee Smith
Greenhorn

Joined: Aug 29, 2006
Posts: 2
Yes, it is bad coding when there is a cleaner method using the if--if else, but they both work regardless.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
In the above case I would probably just use the if / else if structure. But for anything more than two consecutive ifs, I would strongly consider alternatives. A switch statement is a possibility, but very often I would prefer to look up something in a HashMap or array instead. The thing being looked up may even be a command object, representing an action to be taken once the execute() method is called. (Or perform() or run() or whatever you want to call it.) That may be a bit advanced for the beginner forum, so don't worry if it doesn't make a lot of sense right now - but be aware that there are other alternatives that you may wish to investigate later.


"I'm not back." - Bill Harding, Twister
Nathan Leniz
Ranch Hand

Joined: Nov 26, 2006
Posts: 132
Is it bad practice to use the =()?: kind of statement?


And if it is acceptable to use that kind of statement, can I pass it a more beefy argument like


The very existence of flamethrowers proves that at some time, some where, some place, someone once said to themselves "I'd really like to set those people on fire over there, but I just can't get close enough".
Paul Clapham
Bartender

Joined: Oct 14, 2005
Posts: 18541
    
    8

Sure, those are okay. In my opinion that is. But what about this:Here we have a nested tertiary operator, which many might think was going too far. All things are good in moderation but can be taken too far.
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
Moderation, schmoderation! The duoternary operator works great in Comparable / Comparator implementations:

You should code like this as much as possible so that it becomes more well-known. Because I'm tired of people looking at me funny when they see it.
Nathan Leniz
Ranch Hand

Joined: Nov 26, 2006
Posts: 132
Could I take it as far as this without violating any style rules?

varA = total < 5 ? 0 : total < 8 ? 1 : total < 11 ? 2 : 3;

It seems to be the same as



Not asking to be smart, but it compiles fine and does what I want, and it really seems like an easy way to say what I want without typing a lot of lines of code.
[ December 14, 2006: Message edited by: Nathan Leniz ]
Marilyn de Queiroz
Sheriff

Joined: Jul 22, 2000
Posts: 9044
    
  10
Originally posted by Nathan Leniz:
Could I take it as far as this without violating any style rules?

I suppose it depends on the style rules of the company you are working for. Personally, I remember my first job programming professionally, I ran into something similar to Jim's example and it took me quite a while to figure out what the author was trying to do. I prefer to read code without working quite so hard to understand it.

Martin Fowler said, "Any fool can write code that a computer can understand. Good programmers write code that humans can understand."


JavaBeginnersFaq
"Yesterday is history, tomorrow is a mystery, and today is a gift; that's why they call it the present." Eleanor Roosevelt
Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671
[Nathan]: Could I take it as far as this without violating any style rules?

That depends what style rules you're using. A few guides won't want you to use the ternary operator at all. Or maybe you're only allowed one per statement. Or no nested ternary operators (and it's arguable whether your example could be considered nested). There's no definitive answer to this.

Consider, also: the first time someone sees something like this, it may be harder for the read. The second time, it's easier. So if you're just going to do this once, it's probably not worth it. Instead, try to use this style as frequently as possible. Just for Marilyn.

On a slightly more serious note, when I do write code like this, I often insert line breaks for readability. These group the alternatives more readably than parenthesis, in my opinion.

This sort of thing most often seems to appear in Comparators:

I actually do find it's advantageous to write Comparators like this - by grouping the alternatives right next together, it's easier for me to see the overall pattern of the code. If you just have to write one Comparator, it may not be worth it, as it's too nonstandard for some people. But if you've got a lot of different Comparators in your code, the style will quickly become familiar, and the benefits become more significant.
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18545
    
  40

You should code like this as much as possible so that it becomes more well-known. Because I'm tired of people looking at me funny when they see it.


I too, use the ternary operator often -- and whole heartily agree with Jim on this.

However, you better be confident with this tact, because quite frankly... it is very likely, that you will be challenged in your next code review. (There are too many anti-ternary operator developers out there)

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Russell Peters
Ranch Hand

Joined: Jan 25, 2006
Posts: 50
Originally posted by Henry Wong:


I too, use the ternary operator often -- and whole heartily agree with Jim on this.

However, you better be confident with this tact, because quite frankly... it is very likely, that you will be challenged in your next code review. (There are too many anti-ternary operator developers out there)

Henry


I agree..

As a New Year's Wish ...I would want all code reviewers to be programmers and coders ...as in "hands on" so that they would understand what we do without us having to explain such simple things to them.

Well..that could be a new thread in the Meaningless Drivel section which explores the gaffes of the coding world!


SCJP 1.4
Dan Fowler
Greenhorn

Joined: Jan 11, 2007
Posts: 3
One thing to take into consideration using the ternary operators is if your code will be ever be inherited by other developers. The ternary operators may be 'slicker', but because many people don't understand them it may really throw them off if they end up maintaining your code some day. So it may cause a hiccup on some teams. Just something to think about. Good luck.
Doc Ahrens
Greenhorn

Joined: Feb 17, 2007
Posts: 1
I was asked in an interview how to optimize:

if( x == 0 ){
// do something
}else if( x == 2 ){
// do something else
}else if( x == 5 ){
// do another thing
}else if( x == 7 ){
// do yet another thing
}

And he said the answer was that switch would be better because it would only take two steps, rather than having to evaluate through each item, but wouldn't a switch have to evaluate through each item in the switch (like the "if else" would) and therefore take just as much evaluation time? I would like to know.

[ February 17, 2007: Message edited by: Tim Ahrens ]
[ February 17, 2007: Message edited by: Tim Ahrens ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: If Statements
 
Similar Threads
Flow Control: the RETURN statement
Exam Objectives Flow Control.
Understanding continue...label do...while
return statement from Constructor
fall - through for if-else loop ???