28
saiphp
8y

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() {
}
}
}
😠😠😤🙅😢

Comments
  • 2
    2-3 nested scopes inside a function is a good thumb rule. Using this rule what you suggest is a good practice
  • 4
    Your 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. :)
  • 1
    Couldn't you change that to a switch? Or am I missing something.?
  • 1
    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?
  • 0
    @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?
  • 1
    Nested loops seem more painful to me.
  • 1
    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 :)
  • 2
    I 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..
Add Comment