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

Cleaning up a three-factor if statement

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

Problem

A method that I'm working on in a C# project includes the following:

if (isDailyRateRequired) 
{
    CalculatedDailyRate = dailyRate;
}

if (isWeeklyRateRequired) 
{
    CalculatedDailyRate = weeklyRate / 7;
}

if (isMonthlyRateRequired) 
{
    CalculatedDailyRate = monthlyRate / 30;
}


There has to be a cleaner implementation than this. I could compress it to one line with a set of nested ternary operators, but that would be pretty much unreadable.

Other suggestions?

Solution

By looking at your code it appears to me that your basic problem is that isDailyRateRequired, isWeeklyRateRequired and isMonthlyRateRequired are distinct boolean variables instead of an enum. If you just turned them all into an enum things would be a lot more simple, there would be no possibility of inconsistencies between their values, and you would not even have this multiple-choice issue.

Context

StackExchange Code Review Q#7447, answer score: 12

Revisions (0)

No revisions yet.