Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

function with lots of if else's blocks. Can these be removed

Tags:

c#

.net

I have a function that needs to check a datetime against a supplied datetime. My function is shown below (it works fine however I don't like it). The only thing that needs to change is the operator but currently I have a few if, else if's etc & lines of code that have been copied.

I'm sure I'm being stupid and there is a much better way of doing this?

 enum DateTimeOperator
 {
        Equals = 0, GreaterThanOrEqualTo, GreaterThan, LessThan
 }

My function

 bool DateChecked(DateTime dateCheck DateTimeOperator dateOperator)
 {
       if(dateOperator == DateTimeOperator.Equals)
       {
           if (File.GetLastWriteTime(filePath + fileName).Date == dateCheck .Date)
                        return true;
                    else
                        return false;
       }
       else if(dateOperator == DateTimeOperator.GreaterThanOrEqualTo)
       {
           if (File.GetLastWriteTime(filePath + fileName).Date >= dateCheck .Date)
                        return true;
                    else
                        return false;
       }
       else if(dateOperator == DateTimeOperator.LessThan)
       {
           if (File.GetLastWriteTime(filePath + fileName).Date < dateCheck .Date)
                        return true;
                    else
                        return false;
       }
 }
like image 518
mHelpMe Avatar asked Jan 08 '23 13:01

mHelpMe


1 Answers

Just for fun without if/switch:

Dictionary<DateTimeOperator, Func<DateTime, DateTime, bool>> operatorComparer = new Dictionary<DateTimeOperator, Func<DateTime, DateTime, bool>>
{
    { DateTimeOperator.Equals, (a, b) => a == b },
    { DateTimeOperator.GreaterThanOrEqualTo, (a, b) => a >= b },
    { DateTimeOperator.GreaterThan, (a, b) => a > b },
    { DateTimeOperator.LessThan, (a, b) => a < b }
};

bool DateChecked(DateTime dateCheck, DateTimeOperator dateOperator)
{
   //TODO: add a sanity check
   return operatorComparer[dateOperator](File.GetLastWriteTime(filePath + fileName).Date, dateCheck .Date);
}
like image 173
sloth Avatar answered Jan 22 '23 23:01

sloth