When it comes to conditional logic, I always try to ask myself 'how important is readability for this code block' i.e is this something that would change as my project progresses, and further than that, am I the only maintainer of the code? If it is highly volatile code (subject to change often) and if I am not the sole maintainer, then I err on the side of rewriting nested conditionals. I don't think nested blocks are generally bad, but I can't think of a case where they outperform inversion of conditions to single statements, except I guess in terms of mental overhead.
Please note that the brevity of my example relies upon a strong type system with at least basic generics support.
Interesting google terms:
Discriminated Unions
Functional programming
Monads
Haskell (or Hindley-Milner type systems)
Lodash (decent javascript functional library, though this may be a little opaque unless you experiment with a FP language for a while)
When it comes to conditional logic, I always try to ask myself 'how important is readability for this code block' i.e is this something that would change as my project progresses, and further than that, am I the only maintainer of the code? If it is highly volatile code (subject to change often) and if I am not the sole maintainer, then I err on the side of rewriting nested conditionals. I don't think nested blocks are generally bad, but I can't think of a case where they outperform inversion of conditions to single statements, except I guess in terms of mental overhead.
So for instance I would tend to write this
Instead of this
So I guess the question is more down to the conditions the code exists in, rather than the immediate computational benefits of nested vs alternatives?
This is a really great question
And now with monads....
Please note that this example is bad because it appears to rely on side effects
I have googling to do it seems
Please note that the brevity of my example relies upon a strong type system with at least basic generics support.
Interesting google terms:
Discriminated Unions
Functional programming
Monads
Haskell (or Hindley-Milner type systems)
Lodash (decent javascript functional library, though this may be a little opaque unless you experiment with a FP language for a while)
Thank you for this. I'll add it to this weekends reading list.
And what about:
Easy to read and no nested code.
That works too. The lack of braces is just my lazy inner java dev showing