Where to check if an object is null or not?

前端 未结 13 1491
广开言路
广开言路 2020-12-17 10:18

Where do you check if an object that you are passing to a method is null or not?

Should an object need to be tested before calling a method? or within the method tha

13条回答
  •  心在旅途
    2020-12-17 10:57

    I prefer null checks inside methods for two reasons.

    1. I think functions should be 'complete', ie handle null values/'edge cases' and not rely on callers. This is for two reasons,

      • someone calling the method later might forget to add null checks
      • it's easier to test the method with edge cases in unit tests.
    2. having null checks inside the method reduces overall number of null checks inside the code, which usually means more readable code

提交回复
热议问题