Static methods?
In the following I'll use the expression "static methods" about properties as well.
I don't like static methods/properties, but sometimes I have to use them because they are part of some framework. I don't like them because they create (somewhat) hidden dependencies in my code. They also make unit testing difficult. So, when they are part of a framework, I do the following instead of using them directly.
I create an interface and an implementation that calls the static method that I don't want to use directly in my code.
public interface IDateTime
{
DateTime UtcNow { get; }
}
public class DateTimeAdapter : IDateTime
{
public DateTime UtcNow
{
get { return DateTime.UtcNow; }
}
}
This example is C# with the DateTime.UtcNow method as an example but it could be any other static method.
Then, I use it in the following way:
public class SomeController : Controller
{
private readonly IDateTime _dateTime;
public SomeController(IDateTime dateTime)
{
_dateTime = dateTime;
}
//more code here...
}
In this class I would write:
_dateTime.UtcNow
to get the date-time and everything would work normally.
The fact that this class is dependent on "getting a date-time" is clear, since it takes in an object in the constructor, so you cannot use the, SomeController class, without sending in an object of a class that implements the IDateTime interface.
In this example I used dependency injection to automatically inject the appropriate object. (not shown here).
When it comes to unit testing the SomeController class, I can send in a mock-object that returns a specific date-time of my choosing, making it possible to unit test with different date-times. The alternative to this approach, just using the DateTime.UtcNow call directly, would make it impossible to unit test the SomeController class with different date-times, since the call to DateTime.UtcNow would always return the servers date-time.