I really like functional programming in C#, it gives you a lot of flexibility. I am wondering if it is the right idea to use functions instead of helper methods, and to make the code more readable.
So here is what I want, I have a method that needs to find Saturday and do something with it:
public void SomeMethod()
{
var saturday = DateTime.Today;
while (saturday.DayOfWeek != DayOfWeek.Saturday)
saturday = saturday.AddDays(-1);
//rest of the code
}
The problem I am having with this code is readability. I have to scan through 3 lines of code to understand that it needs to find Saturday. Plus seeing var saturday = DateTime.Today;
, it really bugs my eyes.
Of course I can write a helper method
private DateTime GetSaturday()
{
var saturday = DateTime.Today;
while (saturday.DayOfWeek != DayOfWeek.Saturday)
saturday = saturday.AddDays(-1);
return saturday;
}
Now I know exactly what the method does but my problem now is that I know that I won't be calling this method anywhere in the class so it kind of pollutes my class.
So here we are at my favorite:
public void SomeMethod()
{
Func<DateTime> GetSaturdayFunc = () =>
{
var date = DateTime.Today;
while (date.DayOfWeek != DayOfWeek.Saturday)
date = date.AddDays(-1);
return date;
};
var saturday = GetSaturdayFunc();
//rest of the code
}
Although it's a bit more code now my class is not polluted with a lot of utility methods and it is more readable.
What do you think? Is this a good way, are there any better ways?
EDIT
I could also create an extension method which in this case would be appropriate, something like
DateTime.Saturday()
but that's not what I am referring to in my question. I am asking if it is a good practice to wrap a portion of the code as a function inside that method (since that peace of the code will only be used inside that method and might not apply anywhere else), just for readability purposes.