In this blog post I will present 5 ways to declutter your code getting rid of unnecessary if-else statements. I will talk about:
default paramet...
For further actions, you may consider blocking this person and/or reporting abuse
Suppose you have a code like this:
You can use something likes this instead of the example above or switch case:
Personally, I'm a little torn on this pattern. It's compact, and I've definitely used it.
But, IMHO, it increases the cognitive load of the code, you now have two places to look for what it's doing.
For that reason in some instances I use this:
or this:
And performance impact. Using a map (object whatever the name) should introduce indexing operation in the background. On the other hand what if arg = null or arg = 123 or so? You need to handle all the cases instead of having simple switch with the default. Or even just using if's until you actually need more than 3 cases.
I doubt there is any real world performance issue here. And as soon as you have more than 2 cases, this is much more readable than a bunch of if statements.
Regarding handling arg=null or arg=123, I don't think I see the issue.
That is handled by the
part.
I highly doubt that using objects instead of switches and ifs has same performance. I'm not limiting it to this scenario but talking about generic overview why should one avoid switches and ifs in favour of objects or hash maps. Reason I'm asking is because I know for a fact that compilers (including JIT ones) and maybe some interpreters have really good optimizations which can even remove branching in some cases but I have no idea would such thing kick in for objects in JS. I know that c++ compiler since 2017 or so has really good optimizations that can turn generics, branching, hahsmaps into few instructions all together. There was a nice conf were, I forgot his name, wrote code on left side and on the right there was assembly outout. I also know JIT in Java will sometimes kick in an replace some of your code with shorter instructions than on first complie. Question is will such things be done by WebKit or others for JS.
Reagarding the safety again it's about generic thing not thi particular piece. It's much easier to have switch with default case and even shorter than objects and relying that || will not be forgotten
I think we are both right here.
You are right that there probably is a difference in performance.
And I am right that in the real world it will make no difference*.
I learned to always prefer readability and then profile if something is slow. It is usually not what you think that is slowing you down.
*Except in that 0.001% weird edge case
Fyi . The c++ tool mentioned would be godboldt.org.
I like too use mapping objects for everything, but never put a default inside the function. So all my attention is driven to the object. If the function doesn't find a value in the object, it does nothing and returns null, if needed a value.
"too" was mistype, but let it be
Yeah, it's definitely less "user-friendly" or "beginner-friendly". Coming from Ruby, it gave me chills but also I was really excited for the shorthand properties so β I'm as torn as you are there!
Oh, yes! Totally β and thank you! I actually wanted to include this as well but had to run for a lecture. I'll include this wonderful example (I may just change the names so it's easier for tired folks to follow) in the blog tomorrow β look for the shoutout!
This thing I use a lot!
At this point I always format if statements as if code block, because condition in if statement could be very long so that return would be lost dangling somewhere outside of field of view which could lead to bad mistakes.
Data structures are good for reducing code's complexity. Sometimes it is clearer to use switch case or if's.
I love these examples β thank you!
Hi there, great article, thank you!
I like to deal with all the error cases first, and then dealing with the heart of the function. Also I like to create small functions that deal with a single responsibility, this is easier to work with IMO.
I have sort of a kink with promises now and I like to put them everywhere. I like the simplicity of chaining functions.
I am not sure turning inherently synchronous code into async is a good idea. Promises are OK (not great - observables are better in many cases) for async operations but I would definitely avoid introducing the complexity for inherently sync operations.
By using this pattern, you are forcing all your code to be async.
If you use
async
your code becomes a bit more natural:This however indicates that it would be probably be smart to remove the
async
and move that to a separate function. That would allow you to use thedivide
function in more scenario's.THANK YOU! YES, I was soooo tempted to touch on Promises but then majority of folks who read my blogs (maybe less so now?) are beginners so I'm planning to write a separate thing on promises in general. However, I'll link your comment in the article because I love your example! Thank you.
This is an awesome demonstration! I need to start learning and living this pattern for larger functionality.
Tip: instead of
something === undefined && something === null
you can writesomething == null
and it matches both undefined and null, and only them.I find it the only valid case to use
==
over===
.That's true, but oftentimes you have a linter which forces to use "eqeqeq"
Only if you have had someone strongly opinioned setting it up :) And even then you have the
null: ignore
option for it.True! Thanks!
Tnx for this list.
Minor feedback in the β¨ guard clauses
It will not return undefined since you do not break the function flow, it will continue to the end and return
""
(empty string).yup,
a solution would be to add a return before the
console.warn
then it would returnundefined
Ah! True. I edited that part and didn't edit the examples. Argh I should write unit tests for my blogs π© Thank you!
That is the way to go! Smart, if all code samples came from actual unit tests eg. Mocha you would also practice the mentality of "placing tests in the first room".
Yeah I might try it in some future blogs. I've always been a fan of TDD but never made space to properly go through all the phases and the process because I felt there was "not enough time". I'm slowly changing this mindset not only because I feel like TDD is really awesome but also because of how the "not enough time" mindset impacts me and my ability to code at times.
One thing I see on occasion,
is the resulting action being calling a function, with the only difference being some logic determining what a certain argument should be
versus
Another one is calling functions with the same arguments, with the only difference being which function to call:
Versus
Thank you for these examples! Coming from Ruby, this is something I definitely instinctively lean towards and catch myself writing sometimes π I'll include you're examples in the blog post!
I think theres a typo in the last example of the 2nd block "OR operator"
this
should be
Ahhhh thank you! That's what happens when you copy examples mindlessly π©
It's very awesome when you use guard clause to handle multiple condition instead of using if elseif else statement.
I'm a big fan of it and always use it to handle conditional statement in my code :).
Ahhhh I'm also such a fan of guard clauses! My first coding language is and was Ruby, which is obsessed with readable and pleasant code so of course, the looong code monsters that JS awakens from the deepest depth of programming hell gave me chills initially. I feel like my brain fries when I read nested
if-else
s... there should be an ESLint rule that obliges devs to draw a flowchart every time they write a nestedif-else
so it's quick and easy to follow :DNice!
This is applied to structured programming and these operators are great.
In OOP you can remove all accidental IFs and elses
How to Get Rid of Annoying IFsΒ Forever
Maxi Contieri γ» Nov 9 γ» 5 min read
Awesome! I've linked up your blog post in mine just now!
I mainly develop in Ruby and that makes me love guard clauses. Even our linter enforces us to use them for the sake of readability, and it looks awesome :)
Ruby π₯° Guard clauses π₯° Ruby Linters π₯°
If you have more than one condition, why you just not using an array rather than or?
Yeah it's one way to do it but that still keeps the same
if-else
(or justno-return-statement
) logic that we want to ideally get rid of. Here I'd also worry about the performance asif-else
is costly and so is looping and here we'd have looping insideif-else
. But I like this example β thank you!Hi there,
I would opt to reject any non-numeric value to compute any calculus.
If you provide a non-number to compute a sum, then the precondition is not valid; therefore, my function would throw an exception.
Nice article! Thanks for bring it us! Best regards.
Hi Sylwia. Great article, congrats!
Let me do some noob questions?
Using [switch] in a situation with many [if/else if], will offer a better performance?
And is there difference by using [switch] or [if] or vice versa on a compiled or non compiled programming language? Like, on C it would be better this, and on JS better that?
Thanks a lot!
Hi @afpaiva ! Thank you for your question!
In comparison with
if/else
statements,switch
statements are a bit faster with small number of cases and get incrementally faster with new conditions. Readability, it seems that devs prefer to readif/else
for two conditions and thenswitch
es for more.There's this great table from O'reilly:
Talking about performance in C is both beyond my expertise and comfort level, sadly!
Hi my code is like below, can u suggest how can I refactor this:
let nestedIfElseHell = (str) => {
if (typeof str == "string"){
if (str.length > 1) {
return str.slice(0,-1)
} else {
return null
}
} else {
return null
}
}
why don't you use like this?
let nestedIfElseHell = (str) => {
if (typeof str === "string && str.length >1) {
return str.slice(0,-1);
}
return null;
}
or
let nestedIfElseHell = (str) => {
if (isStringAndHasLength(str)) {
return str.slice(0,-1)
}
return null;
}
let isStringAndHasLength = (str) => typeof str === "string" && str.length > 1
Definitely! I like that you are using the typical for OOP callbacks to do the
if/else
job! Thanks!oh hi! I didn't realize I knew who wrote the article until I got to the comments lol. good post!
hello! β¨ good to see you here! it's funny how the tech world is both big and small π
Since your shorting out the code I expected something like
yeah, that totally works too! Thanks for this comment!
I always try to balance how much I'm shortening the code vs how long the blog post is as my blogs posts are oftentimes read by folks with not much programming experience. Sometimes, I prefer to introduce changes incrementally or even not to introduce something because I also trust that the readers (just like yourself) would dig more or even find better solutions β¨
I've been using guard clauses for a while but I didn't know they were called like that!
Great post π
Thank you! Yeah they definitely β¨ spark joy β¨
JS has more useful features that make my life easier when writing conditions. Thank you
I think after starting to use Typescript I haven't had most of these problems
"Geeezz, skip all these and just use typescript."
:/
Oh my! Poor Javascript developers.
Can you help me refactoring dev.to/chitreshgoyal/refactor-java... code