Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
matanl26478y2-3 nested scopes inside a function is a good thumb rule. Using this rule what you suggest is a good practice
-
civel1138yYour hate for that is justified and you're not the only one. Look up: 'arrow head anti-pattern'
Your fix is also known as 'guard clauses'.
I find myself stumbling upon, and fixing, these frequently in a few of the codebases that I work in. I feel your pain. :) -
I think I'm missing something... Those statements are different. The first bit of code would return something depending on value, nothing further. The second part with the nested IFs would return something dependent on further specifications after initial IF...
Nested IFs and Switch-Cases are quite different, no? -
@runfrodorun I get that part, I assume your code would be something actually as:
function(arg){
if (!arg) { return; }
//code
//code...
return;
}
Are you saying some people do:
function(arg){
if (arg) {
//code
//code
return;
}
}
instead? Or am I really missing somethin', haha? -
I like nested more, it's just my preference, however if I'm working with a team and they don't want ifs nested, I won't do it :)
-
Benji-dev198yI usually take this kind of approach to refactoring them:
----------------
if (token) {
let decoded = jwt.decode(token)
let today = new Date()
let tokenExp = new Date(decoded.exp)
if (today <= tokenExp) {
router.push({ path: 'login'})
}
}
-------------becomes
if (!token || tokenExpired(token)) {
router.push({ path: 'login'})
}
tokenExpired function(token) {
let decoded = jwt.decode(token)
let today = new Date()
let tokenExp = new Date(decoded.exp)
return (today <= tokenExp)
}
___________
encapsulating the nested conditional logic to it's own function and making use of && or || for combining..
Related Rants
Refactoring nested ifs.
I'm not a pro but I despise working with nested ifs. It's hard to debug and read.
If you cant chunk the if using method, i think you can use ifs like this:
If(){return}
If() {return}
Not like this:
If() {
If() {
If() {
}
}
}
😠😠😤🙅😢
undefined
sl
nested if