HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpModerate

Complex if else

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
elsecomplexstackoverflow

Problem

How would you write this?

string halfADayOff = "Half a day off";
string oneDayOff = "One day off";
string days = "NoDaysOff";

if (typeOfDelegation)
    {

        if ((differenceInDays == 0) && (arrivalDay.TimeOfDay.Hours > 22))
            days = halfADayOff;
        else if ((differenceInDays == 1) && (arrivalDay.TimeOfDay.Hours > 22))
            days = halfADayOff;
        else if ((differenceInDays == 2) && (arrivalDay.TimeOfDay.Hours  22))
            days = oneDayOff;
        else if (differenceInDays > 2)
            days = oneDayOff;
        else return days;
    }

    else
        if (differenceInDays > 29)
            days = oneDayOff;
        else
            return days;

   return days;

Solution

In order to simplify nesting I reordered conditions so that you can deal with simplest cases first, and return result as soon as you know it instead of capturing it in days variable. Also ternary operator looks like a good choice here...

const string noDaysOff = "NoDaysOff";
const string halfADayOff = "Half a day off";
const string oneDayOff = "One day off";
const int lateNightCutoff = 22; //TODO: couldn't come up with better name, update if you find one

if (!typeOfDelegation)
    return differenceInDays > 29 ? oneDayOff : noDaysOff;

if (differenceInDays > 2)
    return oneDayOff;

var arrivalHour = arrivalDay.TimeOfDay.Hours;

if (differenceInDays == 2)
    return arrivalHour > lateNightCutoff ? oneDayOff : halfADayOff;

return arrivalHour > lateNightCutoff ? halfADayOff : noDaysOff;

Code Snippets

const string noDaysOff = "NoDaysOff";
const string halfADayOff = "Half a day off";
const string oneDayOff = "One day off";
const int lateNightCutoff = 22; //TODO: couldn't come up with better name, update if you find one

if (!typeOfDelegation)
    return differenceInDays > 29 ? oneDayOff : noDaysOff;

if (differenceInDays > 2)
    return oneDayOff;

var arrivalHour = arrivalDay.TimeOfDay.Hours;

if (differenceInDays == 2)
    return arrivalHour > lateNightCutoff ? oneDayOff : halfADayOff;

return arrivalHour > lateNightCutoff ? halfADayOff : noDaysOff;

Context

StackExchange Code Review Q#24755, answer score: 18

Revisions (0)

No revisions yet.