Using Constructor Injection, a dependency gets injected to a consumer like this (at least I hope I understood it correctly):
public class SomeConsumer
{
private IDependency someDependency;
public SomeConsumer(IDependency someDependency)
{
if (someDependency != null)
{
this.someDependency = someDependency;
}
else
{
throw new ArgumentNullException("someDependency");
}
}
public void Baz()
{
someDependency.DoSomething();
}
(...)
}
If I were to use the Null Object Pattern for IDependency, do I need the guard clause? Or is it wrong to inject a Null Object?
UPDATE: To clarify, let's assume I have classes and interfaces like this:
public interface IDependency
{
void DoSomething();
}
public class NullDependency : IDependency
{
public void DoSomething()
{
//Do nothing...
}
}
public class RealDependency : IDependency
{
public void DoSomething()
{
Console.WriteLine("Did something");
}
}
public class Foo
{
public void Bar()
{
IDependency dependency = new NullDependency();
SomeConsumer sc = new SomeConsumer(dependency);
sc.Baz();
}
}
Can I then safely remove the guard clause from SomeConsumer, making it look like:
public class SomeConsumer
{
private IDependency someDependency;
public SomeConsumer(IDependency someDependency)
{
this.someDependency = someDependency;
}
public void Baz()
{
//if someDependency is a NullDependency, this does nothing
someDependency.DoSomething();
}
(...)
}
Or should I use the guard clause because I can't be sure that null
will never be injected?