The purpose of the code below is to determine if a particular date qualifies as a "weekend" i.e after 12:00 PM on Thursday, minimum 2 days and before Monday 12:00 PM
Is there a better way? If-Else turns ugly and the Strategy pattern is way too much work for this.
public bool ValidateWeekend(DateTime pickupDate, DateTime dropoffDate)
{
TimeSpan ts = dropoffDate.Subtract(pickupDate);
if (ts.TotalDays >= 2 && ts.TotalDays <= 4)
{
switch (pickupDate.DayOfWeek)
{
case DayOfWeek.Thursday:
if (pickupDate.Hour >= 12)
{
switch (dropoffDate.DayOfWeek)
{
case DayOfWeek.Sunday:
return true;
case DayOfWeek.Monday:
if (dropoffDate.Hour <= 12)
{
return true;
}
return false;
}
}
break;
case DayOfWeek.Friday:
switch (dropoffDate.DayOfWeek)
{
case DayOfWeek.Sunday:
return true;
case DayOfWeek.Monday:
if (dropoffDate.Hour <= 12)
{
return true;
}
return false;
}
break;
case DayOfWeek.Saturday:
switch (dropoffDate.DayOfWeek)
{
case DayOfWeek.Sunday:
return true;
case DayOfWeek.Monday:
if (dropoffDate.Hour <= 12)
{
return true;
}
return false;
}
return false;
}
}
return false;
}
You definitely should refactor the dropoffDate out - because the code is duplicated 3 times! The simplest cleanup: I would introduce a function to check the pickupDate and another to check the dropoffDate:
private bool IsPickupWeekend(DateTime pickupDate)
{
switch (pickupDate.DayOfWeek)
{
case DayOfWeek.Thursday:
return pickupDate.Hour >= 12;
case DayOfWeek.Friday:
case DayOfWeek.Saturday:
return true;
}
}
return false;
}
private bool IsWeekendDropOff(DateTime dropoffDate)
{
switch (dropoffDate.DayOfWeek)
{
case DayOfWeek.Sunday:
return true;
case DayOfWeek.Monday:
if (dropoffDate.Hour <= 12)
{
return true;
}
return false;
}
return false;
}
And now your main function is a 2 liner:
if (ts.TotalDays >= 2 && ts.TotalDays <= 4)
{
return IsPickupWeekend(pickupDate) && IsWeekendDropOff(dropoffDate);
}
I think you could extract a method here:
private bool ValidateDropoff(DateTime dropoffDate)
{
switch (dropoffDate.DayOfWeek)
{
case DayOfWeek.Sunday:
return true;
case DayOfWeek.Monday:
return dropoffDate.Hour <= 12;
default:
return false;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With