Manually validate date/time comes before another

Advertisements

I have to manually verify a time/date format of the type day_hh:mm:ss so 1_09:00:01 comes before another and return a boolean.

Ive come with this but there are still some tests that are not validated correctly. Any ideas where I could refactor?

bool DateHour::operator<(const DateHour& date_hour) const{
    if(days <= dh.days){
        if(hours <= dh.hours || dh.days > days){
            if(minutes <= dh.minutes || dh.hours > hours || dh.days > days ){
                if(seconds < dh.seconds || dh.minutes > minutes || dh.hours > hours || dh.days > days)
                    return true;
                else if(days == dh.days && hours == dh.hours && minutes == dh.minutes && seconds == dh.seconds)
                    return false;
                return true;
            }
            return false;
        }
        return false;
    }
    return false;

>Solution :

Attempting to squish days/hours/minutes/seconds together into one combined chunk of logic, in the shown code, leads to many hard to understand logical flaws. The easiest way to solve a complicated problem is break it up into smaller problems, and solve them individually.

if(days < dh.days)
    return true;

if(days > dh.days)
    return false;

And now the problem is solved when the number of days are different, and the logic is provably correct.

At this point, a brilliant observation becomes obvious: now that the days are the same, the same exact logic simply gets repeated for the hours:

if(hours < dh.hours)
    return true;

if(hours > dh.hours)
    return false;

Still just as simple, and just as provably correct. And repeat the exact same thing for minutes and seconds.

In the end, everything is the same, so the grand conclusion is just a

return false;

"The more you overthink the plumbing, the easier it is to clog up the drain" — Scotty, Star Trek III.

Leave a ReplyCancel reply