loading...

re: There's no "else if" in JS VIEW POST

TOP OF THREAD FULL DISCUSSION
re: There is a golden rule: if statement is always a sign of a design flaw. Period.
 

Then why is it there in the language? To put in other words, where does it make sense to use an if-else statement?

 

There are many things in modern languages that are just a matter of legacy. In procedural programming era (the most noticeable example would be FORTRAN) there were no paradigms to avoid conditionals. Nowadays we have plenty.

Using ifs inevitably leads to spaghetti code, that is hard to read and incredibly hard to maintain. Also, if violates the SRP principle out of the box.

Yes, sometimes if might be the best solution (when there are two possible outcomes, and there will be two forever, e.g. if hours < 12 then 'AM' else 'PM',) but the list of usages is very limited and in general there [nearly] always would be a better, cleaner and easier to support alternative.

This is incorrect. The inclusion of if isn't a matter of legacy, it's because if is a low level primitive that can be used to build higher level abstractions. That is why Lisp has if; the thesis of Lisp is to expose a small set of primitives, allowing developers to leverage those primitives to build the language they need. While I agree that many developers reach for if when a higher level of abstraction would be more appropriate, there should be no golden rule to "never use if". Sometimes a lower level of abstraction is what is appropriate for a task.

 

While I don't agree wth the premise that if is inherently bad in a non-functional programming language, having something in a language doesn't make it good. Many languages are extremely poorly-thought-out and nothing's perfect.

 

Saying that if-else statement are always bad isn't something I would do. As any other tools, it has to be use in the right place to be effective.
Sometimes, I do prefer a switch (or match expression). But sometimes, it just do not make any sense to avoid the if-else. As an example, when coding a game, you might want to know either or not an object is in front of the player. You will certainly use the dot product as it is cost efficient and then you will have to test if the result is zero or if it is a positive number above zero.
From my point of view, the if-else fits perfectly here. Again, his use has to be cautious.

At least, I think so.

code of conduct - report abuse