How much null checking is enough?

后端 未结 18 996
清酒与你
清酒与你 2021-01-30 01:10

What are some guidelines for when it is not necessary to check for a null?

A lot of the inherited code I\'ve been working on as of late has null-checks

18条回答
  •  旧巷少年郎
    2021-01-30 01:14

    It depends on the situation. The rest of my answer assumes C++.

    • I never test the return value of new since all the implementations I use throw bad_alloc on failure. If I see a legacy test for new returning null in any code I'm working on, I cut it out and don't bother to replace it with anything.
    • Unless small minded coding standards prohibit it, I assert documented preconditions. Broken code which violates a published contract needs to fail immediately and dramatically.
    • If the null arises from a runtime failure which isn't due to broken code, I throw. fopen failure and malloc failure (though I rarely if ever use them in C++) would fall into this category.
    • I don't attempt to recover from allocation failure. Bad_alloc gets caught in main().
    • If the null test is for an object which is collaborator of my class, I rewrite the code to take it by reference.
    • If the collaborator really might not exist, I use the Null Object design pattern to create a placeholder to fail in well defined ways.

提交回复
热议问题