Search code examples
language-agnosticreadabilityboolean-logic

Simplifying if statement logic


I have seperated out a test to determine if two schedule items overlap because of the unreadability of it.

Is there any application to assist in simplifying a logic statement?

Example: (originally a faulty example, but exposes reasons I request this)

if (x < y && y < z && x < z)  

could be reduced to

if (x < y && y < z)

My code is:

return (shift.Start <= shift2.Start && shift.End >= shift2.End) || (shift2.Start <= shift.Start && shift2.End >= shift.Start)

I would love to make that simpler, and I believe it's possible, just unsure how.

Seeing as this is really language agnostic, even converting to a different script to find possibilities would be nice, no need for it to be in C# for instance.


Solution

  • When it comes to complex logic statements, you're usually best off with formatting your code in a readable manner than attempting some premature optimization (root of all evil, etc.)

    For example:

    return (shift.Start <= shift2.Start && shift.End >= shift2.End) || (shift2.Start <= shift.StartTime && shift2.End >= shift.Start)
    

    Can, for readability and maintainability, be refactored to:

    bool bRetVal = false;
    bRetVal = (    (   (shift.Start <= shift2.Start)
                    && (shift.End >= shift2.End))
                || (   (shift2.Start <= shift.StartTime)
                    && (shift2.End >= shift.Start)))
    return bRetVal;
    

    Most places maintain a coding standard that defines something like the above for large logic blocks. I'd much rather maintain a few extra lines of code that can be read and understood than a one line monstrosity.