DEV Community

Discussion on: When is nesting good or neutral?

Collapse
 
cishiv profile image
Shivan Moodley • Edited

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

function conditionalsOrNo() throws AnException {
    if (!codeIsNotVolatile) throws new YouShouldRefactorException()
    if (!codeIsMaintainedByMe) throws new WhyAreYouTryingToCauseYourselfPainException()
    return writeConditionals()
}

Instead of this

function conditionalsOrNo() throws AnException {
    if(codeIsNotVolatile) {
        if(codeIsMaintainedByMe) {
            return writeConditionals()
        } else {
            throws new YouShouldRefactorException()
        }
    } else {
        throws new WhyAreYouTryingToCauseYourselfPainException()
    }
}

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

Collapse
 
jbristow profile image
Jon Bristow • Edited

And now with monads....

fun conditionalsOrNo(maybeCode: Either<Error, Code>) = maybeCode.map(Code::writeConditionals)

Please note that this example is bad because it appears to rely on side effects

Collapse
 
cishiv profile image
Shivan Moodley

I have googling to do it seems

Thread Thread
 
jbristow profile image
Jon Bristow

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)

Thread Thread
 
cishiv profile image
Shivan Moodley

Thank you for this. I'll add it to this weekends reading list.

Collapse
 
lito profile image
Lito

And what about:

function conditionalsOrNo() throws AnException {
    if (!codeIsNotVolatile) {
        throws new YouShouldRefactorException();
    }

    if (!codeIsMaintainedByMe) {
        throws new WhyAreYouTryingToCauseYourselfPainException();
    }

    return writeConditionals();
}

Easy to read and no nested code.

Collapse
 
cishiv profile image
Shivan Moodley

That works too. The lack of braces is just my lazy inner java dev showing