- Home /
Using else if
I've seen it mentioned a few times on the forums that you should never use "else if" in code.
Now, I understand that it can be easily abused. If you have an if statement that has 20 "else if" statements within it, you're probably doing something wrong (or, at least, inefficiently). However, do people really mean NEVER use "else if"? Or do they just mean to use it rarely?
It's me that says this.
What is meant is: never, ever use them. NEVER !!
NEVER, EVER !
It's just a crap control structure. It's like having a dangling block or using gotos or globals [footnote]** or using incredibly poor variable names.
"If" is fine. "If-else" is fine. "for" is kind of crappy. "while" is good. things like "until" are just pointlessly too clever for their own good. "else if" is just crap.
one simple problem: what does it mean? nobody knows or can explain it. Do you know? I don't, and you don't.
Good language control structures are beautiful, are immediately, absolutely and utterly undeniable in what they mean, they nest beautifully (the absolute heart of program$$anonymous$$g, after all, conceptually), they are $$anonymous$$ISS, they should just about almost perform like a Group in mathematics looked at the right way.
to repeat - what does "else if" mean? nobody knows. else .. what? what's it referring to? the most recent thing, the first thing, what? it can be implemented slightly differently, under discussion - so it's useless. any computer code you look at should be utterly unambigious
for the record: in some specific situations, gotos are fantastic and should be used. in contrast "else if" is crap that should be taken out of languages.
this actually has almost nothing to do with Unity, I guess! :)
"one simple problem: what does it mean? nobody knows or can explain it. Do you know? I don't, and you don't."
Wha? That's a surprising statement to me. It was as easy for me to understand as "if"... and I don't consider myself a particularly adept programmer. It means "if the thing checked in the original 'if' statement is not true, check to see if this second statement is true ins$$anonymous$$d".
That's why it's so easy to abuse... because beginner programmers DO understand what it does, and think that it's a quick fix. "Hey, I have to check which one of 20 possible things are true. 'Else if' to the rescue!" A switch statement is usually clearer and less verbose.
Right now, I do use "else if", but only in situations in which there are, say, 1 of 3 possible things that might be true. There are certain times in which "else if" just looks clearer, and takes up less space because of not needing a separate line for "break".
"this actually has almost nothing to do with Unity, I guess! :)"
Hmm... you're right. That might explain why I hadn't seen this question answered on the forums. I'll leave it to the judgement of others if it should be deleted.
I think people here are making a bigger deal than it is... If someone ever tells you to "never" use something, it is more than likely they do not know that thing well enough. As long as you understand that you shouldn't use a string of else ifs if it can be avoided. But, if you have something that will be clear to say "if these conditions, do this. Else if these conditions, then do this". If there are just a few, you will be fine.
$$anonymous$$'s answer below is better than fattie's lack of understanding.
I don't know if I'd necessarily a lack of understanding... just an extreme distaste. I've seen similar distaste for other program$$anonymous$$g things (like static variables). It's good to have multiple perspectives.
Answer by dannyskim · Oct 24, 2012 at 06:25 PM
I personally think they mean to use it rarely, or sparingly as it's a poor "logic" choice. When running through a method or a program, if someone is using else if's a lot, it's likely that they're not taking into account all the dynamic possibilities that they may run into.
I think it's perfectly fine to have a string of else if's if the logic is guaranteed to be within a set confines. Even if so, if it can be handled in a switch statement, it should be rather than an else if because then you're forced to handle the step through logic, and ESPECIALLY you're recommended to enforce the default case so that you're wrapping the step through properly with the least amount of possible leaks.
The main reason people declare to never us it, is because it's "more proper" to use a string of ifs and return out of the block of execution, which I don't necessarily agree with. This way, you're handling the step through logic properly, and you're minimizing the comparison's that you need to do, which is why a switch statement is seen as a much better option than a string of else if's, because you're using break to break out of the step through.
Even then, it's not like it's going to make a huge difference if your practices are sound. In the end, I would personally see it simply as a design choice. You either go one way, or you don't.
Good answer. However, I was under the impression that using "else if" would mean that the program would test if the first is true, and if it is, then it wouldn't evaluate any of the other "else if" statements. Is that incorrect?
No it's correct, and I edited my answer to reflect my own opinion. I just wanted to try and address the main question you had, which is why people think that way.
EDIT: To be clear in my opinion, returning out of a big string of if's ins$$anonymous$$d of using if-else if-else is non-sensical to me. If else-if is handled properly, there really is no huge difference I$$anonymous$$O.
if one is using switch statements, one is not thinking algorithmically - something's gone wrong at one's paradigm stage. but, at least it's neat.
if someone is using else if they are almost always lost -- I don't mean that as a glib sentence, what I mean is that epidemiologically, if you look at this site as a sample set, so far every code fragment I have seen that mentions "he who shan't be named" ... is total confusion.
regarding your second paragraph - your second paragraph is utterly correct, final and conclusive: ie, never use else if, use switch - if you don't believe this see $$anonymous$$'s total explanation why.
so that's the end of it .. never use else if. Your 2e para is all correct.
"The main reason people declare to never us it, is because it's "more proper" to use a string of ifs and return out of the block of execution"
not true -- one very important coding technique is to learn how to use return and break. when I tell people, who are totally confused and additionally are using "else if," that they should learn to write "breakaway" code ........ it's like telling an incredibly fat person to start jogging .. it may help with the underlying problem. :)
what you mention about $$anonymous$$imization is not correct (moreover, optimization never matters).
the reason not to use it is (A) it is totally unclear - it has no immediately clear fixed meaning - (B) it is highly inelegant (the ultimate sin in program$$anonymous$$g .. the idea of criticizing say gotos in the face of elsif is nuts) - (C) it is a useless control structure because it is not even close to feeling like it has closure, associativity, identity and invertibility - good control structures do. Example: simply "you can't nest" elsif - it would be insanity, total madness. To the point where you can just flat state "it's not possible". Of course, all other control structures must and do nest beautifully.
$$anonymous$$erely point (A) .. "it is unclear" .. finishes it. If I hypothesised to you some new control structure idea, and you said, well, that's unclear and ambiguous ("....as elsif" ) that would be the end of it.
I agree Fattie, and I personally appreciate your insight. To be honest, the only time that I use else if's is most likely in the case that it's a single use class / script. Take for example, I did a tutorial level for a small game that I did, and I used a switch statement, and later a small string of else if's because I knew things had to happen in ONE way and in ONE way only. It was clear cut.
Browsing through the rest of the code, I only spotted one other place where I actually used it, and even then, I could find a more elegant way to handle it.
@Fattie if I remember the history of program$$anonymous$$g correctly, and the way that processors actually handle all of this:
when the processor sees an if statement with just an if/else if begins to perform what is inside the if block while the comparison is being done, and then if the comparison fails the compiler goes to the next enclosed block.
if the processor sees an if/else if/.../else if does the same as above until it reaches the else block, or one of the comparisons succeed.
in your statements about the case-switch. this shows a lack of understand of what they are. a case switch functions the same as if/else if/.../else (the difference is the number of things you can compare against) the compiler convert case statements to else if just happens behind the scenes.
and for an example of elegance:
if(thing1 == thing2 && thing3 == thing4){ //do code0
}else if(thing2 == thing3 && thing1 == thing4){ //do code1
}else if(thing1 == thing3 && thing2 == thing4){ //do code2
}else{ //do code3
}
if you think about this situation the else if is the most convenient, and elegant solution for a case-switch as soon as the comparisons begin to require conversion, or more then one thing it becomes the most ghastly things ever, and in the case of multiple if statements you are actually wasting more processing time because for each of those if statements when the processor gets there it will begin to perform the actions until the given comparison is complete meaning that if there are 10 if statements there are 10 blocks of code the system will attempt to do, but not complete.
Answer by CG-DJ · Jul 21, 2013 at 01:53 AM
Ok...noob alert here...
From my point of view (I've been working in computer code for about 3 months), else if statements make sense for certain things. Basically, I can denote lines of code to only be called when the first statements are false. For example, if I want to create a simple set of statements to turn a boolean on or off, I need to use else if:
var test : boolean = false;
//when key is pressed
if(test == true)
{
test = false;
}
if(test == false)
{
test = true;
}
this variable will always be true, because it will fun the first if statement, and then immediately run the next if statement.
var test : boolean = false;
//when key is pressed
if(test == true)
{
test = false;
}
else if(test == false)
{
test = true;
}
However, in this statement, the variable will switch from true to false with each button press.
And I'm probably missing something, but this seems like a more simple way to do SOME THINGS. And if it isn't I'd love to be directed to some more learning materials!
Thank you for your time!
Well, else if has some great usages, however your example is, well, a bad choice ;)
Your code could be written in a single line:
test = !test;
Of course often you have to do additional stuff when you toggle a boolean, but in this case that would be more than enough:
if (test)
{
test = false;
}
else
{
test = true;
}
A lot people say else-if-chains are ugly or bad and you should use a switch ins$$anonymous$$d, but there are a lot cases where switch is actually ugly or doesn't fit the case.
A simple example. Think of a player that can perform one action at a time. For this you check if a certain key is pressed. You don't want to execute two actions at once, so if two buttons are pressed at the same time, only one should execute. Some actions might require an additional state, like jumping requires the player to be grounded.
if (actionsBlocked)
{
// Do nothing
}
else if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.W))
{
// $$anonymous$$ove 1 tile up
}
else if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.S))
{
// $$anonymous$$ove 1 tile down
}
else if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.A))
{
// $$anonymous$$ove 1 tile left
}
else if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.D))
{
// $$anonymous$$ove 1 tile right
}
else if (hasWeapon && Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space))
{
// fire weapon
}
else
{
// idle, no action
}
This can't be realised with a switch statement. Using cascaded if-else blocks would actually be ugly like hell. The most important thing when using else-if chains is: Don't put too much code in one block or it get's messy and you can't keep tracking the flow of control. Usually you would just call a function which handles the case.
Yep, you were right about my bad example, because you can use else there. However if I used number values:
if(number > 10)
{
number-10;
}
else if(number < 10 && number > 10)
{
number-5;
}
else
{
number-1;
}
This wouldn't work with if statements because it would complete the first logic statement and change the number, but then go to the second statement and read the changed number. Using an else if statement allow the number to be changed only once!
And yes, I totally understand and agree to not string massive amounts of else if statements. After first reading this thread, I never thought about using them again. I'm just trying to point out that they are useful for small things. Am I right?
That's another bad example... when is (number < 10 && number > 10)
ever going to be true? :)
Answer by Max_Bol · Jun 01, 2015 at 07:30 PM
It's ironic how the "Else If" statement is so bi-angular in the mind of the programmers. Most programmers "boycott" it do it for 2 reasons :
1) Either they have been working with someone's work which was badly scripted and included it.
2) Or they learned it from someone else as a "no go" and keep thinking it.
It's the same as if you're learning to speak English in the U.K. or in the U.S. or French in France or in Quebec (Canada). It's a matter of where you learned it and who's teaching.
Personally, I think it's okay to uses it as conditional statement if you got full control over the conditions. For example, if you make uses of a Random.Range(x,y) and want to apply some specific actions/statements ONCE with uneven range covering.
For example, in a function that is only called once when a chest is opened.
void ChestDrop()
{
int randomDropTemp = 1;
randomDropTemp += Random.Range(0,99);
if(randomDropTemp <= 60)
{
GenerateDrop(1);
}
else if(randomDropTemp >= 90)
{
GenerateDrop(3);
}
else
{
GenerateDrop(2);
}
}
In which GenerateDrop(); have its own switch statement that works with the 1, 2 or 3 integer as its case values. This is a situation in which else if can be useful as it allow temporary predetermined uneven conditional variables to be quickly read and analyzed once and forgotten in the next frame. In the given example, a Switch statement would be difficult since it represent a chance of 60% to getting a drop of quality 1, 10% of getting a drop of quality 3 and the remaining possible 30% of getting a drop of quality 2. There's also no chance of having the randomDropTemp value outside of the predetermined values. Even if for some unknown reason, randomDropTemp gets lower than 0 or higher than 100, it's still covered.
Personally, I would advise people to never listen to words like "it's ugly" or "it's sinful", "it's inelegant", etc. to judge the uses of any statement or function in programming (like in mathematics). Those are used only to put more pressure on the opinion without real logical meaning behind them. The ONLY reason why you should listen to that type of comment is if it has an impact on your future like having one hell of a really close-minded teacher that could make you fail just for it. Otherwise, it's already good to listen to comments like "it won't work with[...]" or "In this case, it can work [...]" because they are logical reasons that "works" regardless of aesthetics.
Aesthetics is always the last of your problems. If you can include it, good. If not, don't bother with it and practice so that, once day, you can include it. That's the same with "ugly", "sinful" and "inelegant" comments.
Things like this :
Should be your priority.
Only when you have fully finalized your work that it should looks like this :
(Note that those picture are not the same equations... it's only for showing what I meant visually)
Damn even the example I have given, personally, for the sake of making it simple and as much forgettable as possible, I even tend to not format it as big as that... more like :
void ChestDrop()
{
int randomDropTemp = 1; //Temporary int for drop quality
randomDropTemp += Random.Range(0,99); //Will result between 1 and 100
//Get and send the random-based drop quality to GenerateDrop
if(randomDropTemp <= 60){GenerateDrop(1);}
else if(randomDropTemp >= 90){GenerateDrop(3);}
else{GenerateDrop(2);}
}
Well, that's my opinion.
Answer by himanshugupta159 · Jan 22, 2019 at 06:35 AM
Writen a blog related to full concept of condition statements the link is attached below: https://unfragilecoding.blogspot.com/2018/04/statements-if-if-else-if-else-if.html
Your answer
Follow this Question
Related Questions
Should player & pickups be children of the level, or keep them separate? 2 Answers
Noob question about best practice in managing game data 2 Answers
2D Openworld transport game. How to generate the tracks? 0 Answers
Animation and good practices 0 Answers
Should I be using Scriptable Objects that only contain a method implementation? 1 Answer