Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

Required fields*

6
  • What is your question? Commented Dec 6, 2013 at 8:08
  • 1
    Its there in Title "Should we always write Defensive check in code?" Commented Dec 6, 2013 at 8:10
  • 3
    The answer is "it depends", and is too broad to answer. See How necessary is it to follow defensive programming practices for code that will never be made publicly available? an Defensive Programming Techniques for some great pointers. "Is that will make extra burden for compiler? etc" isn't really a concrete, answerable question. Commented Dec 6, 2013 at 8:12
  • 2
    I agree with @CodeCaster - it depends. I see a lot of "defensive" code that does "if (fred != null) { fred.doSomethingVital());}" but does not take any action if fred IS null. All this is defending against is a null reference - it doesn't defend the application at all if the call to fred.doSomethingVital() is actually key to the business operation the application is supporting. In this case it would probably be safer to not check the null reference - at least the code will fail quickly and noisily. Commented Dec 6, 2013 at 8:38
  • I think this depends on how nulls are used in your codebase. If they're a valid output to functions, then yes. If they're representative of a failure state, then the question becomes "can I meaningfully recover from this?", just like it would be with exceptions. Defensively checking for nulls to hide failures earlier in the codebase is just asking for difficult to debug errors. Commented Dec 6, 2013 at 9:34