Null parameter checking in C#

前端 未结 9 541
失恋的感觉
失恋的感觉 2021-01-29 21:46

In C#, are there any good reasons (other than a better error message) for adding parameter null checks to every function where null is not a valid value? Obviously, the code tha

9条回答
  •  深忆病人
    2021-01-29 21:54

    I agree with Jon, but I would add one thing to that.

    My attitude about when to add explicit null checks is based on these premises:

    • There should be a way for your unit tests to exercise every statement in a program.
    • throw statements are statements.
    • The consequence of an if is a statement.
    • Therefore, there should be a way to exercise the throw in if (x == null) throw whatever;

    If there is no possible way for that statement to be executed then it cannot be tested and should be replaced with Debug.Assert(x != null);.

    If there is a possible way for that statement to be executed then write the statement, and then write a unit test that exercises it.

    It is particularly important that public methods of public types check their arguments in this way; you have no idea what crazy thing your users are going to do. Give them the "hey you bonehead, you're doing it wrong!" exception as soon as possible.

    Private methods of private types, by contrast, are much more likely to be in the situation where you control the arguments and can have a strong guarantee that the argument is never null; use an assertion to document that invariant.

提交回复
热议问题