Does it make sense to check for null values in injected arguments?

走远了吗. 提交于 2020-01-15 21:17:17

问题


I am using Unity in my application. Does it make sense to check for null values in the constructor for the injected values?

public class ExampleClass
{
    public ExampleClass(IExampleArgument e)
    {
        if (e == null)
            //Do something
    }
}

Shouldn't the argument be resolved already and bound to a value? And in case a problem happens, it should occur during resolving, so I either have a value here or I don't?


回答1:


Does it make sense to check for null values in the constructor for the injected values?

Absolutely.

Shouldn't the argument be resolved already and bound to a value?

There's nothing forcing clients to use injection - it would be perfectly valid syntactically to call your constructor with a null value. I'm assuming that a null value would cause a problem later in the program, so you decide - do you want to handle the problem in that constructor or let it occur naturally later in the program?




回答2:


The construct you are referring to is a guard clause. It is used to make absolute certain that no invalid values can be used, usually by failing very early (in the case of DI, this is during the construction of the DI container rather than during the application's runtime).

This is an insurance policy that protects against the possibility that a null value could exist. When you consider that you might be using the class in other contexts (such as unit and integration tests), it makes sense to guard against the possibility that invalid input can be used. It makes the entire codebase more robust because you don't have have null reference checking strewn across the entire application - it is checked once at the point of input, and only there.




回答3:


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.



来源:https://stackoverflow.com/questions/34315364/does-it-make-sense-to-check-for-null-values-in-injected-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!