I have read some articles discussing about why static is bad, some of them refering static as not-testable, non-mockable, has state (non-stateless) and everything else.
However I have encountered some cases where I am forced to use static implementation, such as:
- During using HttpContext.Current in Asp.Net, as well as Session
- The HttpContext and Session sometimes contains configurations, which is needed to do some validations
- Accessing some static objects in framework or third-party component
- Maybe there are other situation where I don't yet encountered
Up until now I have handle those static methods using custom adapters (correct me if I misuse the term adapter here, or maybe it is better for provider), such as:
public class ConfigurationAdapter : IConfigurationAdapter
{
public string CurrentUsername
{
get
{
return HttpContext.Current.User.Identity.Name;
}
}
}
Then the consumer will use the adapter like:
public class ConfigurationConsumer : IConfigurationConsumer
{
public ConfigurationConsumer(IConfigurationAdapter adapter)
{
_adapter = adapter;
}
private readonly IConfigurationAdapter _adapter;
public void DoSomething()
{
string userName = _adapter.CurrentUsername;
}
}
I believe that this way I can get the benefits:
- The adapter can be replaced by other implementation
- The adapter can be mocked
- The consumer does not directly dependent on HttpContext
However due to inexperienced in design, I am still wondering about:
- Does this kind of implementation can really decouple the consumer with the static object?
- Will it provide any problem in the future?
- Is there any better design or pattern than this?
In this case I want to make sure that my application is testable, maintainable dan extendable. I believe performance is not effecting too much here, so it can be ignored.
Any kind of thoughts will be appreciated