Just trying to still get my head around IOC principles.
Q1: Static Methods - Should util classes with static helper methods be wired up with IOC?
For example if I have a HttpUtils class with a number of static methods, should I be trying to pass it to other business logic classes via IOC?
Follow on questions for this might be:
Q2: Singletons - What about things like logging where you may typically get access to it via a Logger.getInstance() type call. Would you normally leave this as is, and NOT use IOC for injecting the logger into business classes that need it?
Q3: Static Classes - I haven't really used this concept, but are there any guidelines for how you'd typically handle this if you were moving to an IOC based approach.
Thanks in advance.
The funny thing about IoC is that objects written in the style are generally decoupled from those details.
Let's use the utility class as an example:
public class HttpUtils
{
public static void DoStuff(int someValue)
{
// ...
}
}
In a non-IoC-focused application, you might use that method directly:
public class Foo
{
public int Value { get; set; }
public void DoStuff()
{
HttpUtils.DoStuff(Value);
}
}
However, that couples the definition of DoStuff
directly to its implementation. IoC strives to divorce those kinds of details, so instead we define the operation on its own:
public interface IDoesStuff
{
void DoStuff(int someValue);
}
Then, we leave room in Foo
for the implementation to change:
public class Foo
{
private readonly IDoesStuff _doesStuff;
public Foo(IDoesStuff doesStuff)
{
_doesStuff = doesStuff;
}
public int Value { get; set; }
public void DoStuff()
{
_doesStuff.DoStuff(Value);
}
}
This decouples Foo
from HttpUtils
. The implementer of the concept of DoStuff
is now a configuration detail, and not an inherent dependency (as it is with the static method).
Notice that Foo
has no idea if its IDoesStuff
is a singleton or not. That lifetime is also a configuration detail, and not an inherent detail of Foo
.
To sum up, IoC and static
are generally at odds, since IoC promotes change and static
, by definition, prevents it. Declare your dependencies in your constructors, and you'll find you almost never have you use static
functionality.