peterc
peterc

Reputation: 7883

Best practice: Is there any point in using an argument Guard for dependency injected objects

This is a best practice question.

One of our C# coding guidelines my team uses states that we use an argument guard for all arguments passed to public methods.

So, we have the guard method something like...

public void Guard (object obj, string name)
{
   if (obj == null)
     throw new ArgumentNullException($"{name} should not be null");
}

And then we use it like

public void MyMethod(MyObject myObject)
{
   Guard (myObject, nameof(myObject)):
   ....
}

An internal team discussion came up the other day on whether there is any point in using this for dependency injected objects in a constructor? I would have thought perhaps not, as the DI framework would already throw an exception if the object type to be injected is not registered.

Opinion within the team was divided, and just wanted to see what the broader community opinion was.

Thanks in advance.

Upvotes: 1

Views: 267

Answers (1)

Jan Muncinsky
Jan Muncinsky

Reputation: 4418

When you design your class, you cannot automatically assume, that it will be managed by IoC container. Somebody may take your class and use it without IoC. So considering this fact, it makes sense to protect your constructor against null input.

Moreover containers I know allow injection of custom instance, which can be even null reference. So without protection in constructor, this could be possible, but you can effectively prevent it.

Upvotes: 1

Related Questions