Where to check if an object is null or not?

前端 未结 13 1516
广开言路
广开言路 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:54

    You can design a method to work with valid objects only.

    That means you are expect to receive valid objects ( not null in your case ).
    That means you don't know how to react and what to do with invalid objects:

    • returning silently from the function is not a solution;
    • throwing an exception will mean you move responsibility to the upper methods where they can check the value already before passing to you.

    So if your method don't know exactly how to handle invalid object and the method won't follow additional logic in the invalid case you should put

    Debug.Assert( Person );
    

    at the PrintAge begin and this will force you to make checks upper by call stack.

    The lower function in hierarchy is the less checks it should do. The following is disadvantages of doing checks in the functions that do the work.

    • Function that is doing actual work has to be as clear as possible without mass of ifs
    • Function will be called more then many times
    • Such function can call such functions and they can call such functions again. Each of them will perform the same validation

提交回复
热议问题