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 that is using the argument?
public class Program { public static void Main(string[] args) { // Check if person is null here? or within PrintAge? PrintAge(new Person { Age = 1 }); } private static void PrintAge(Person person) { // check if person is null here? Console.WriteLine('Age = {0}', person.Age); } } public class Person { public int Age { get; set; } }
Having a ‘null’ check in both classes seem to be too much redundant code.
[EDIT]: What would be an dis/advantage of checking for null within a caller or a callee?
[EDIT2]: I just ran into Defensive Programming and it seems like it advocates checking null within a callee. I wonder if this is a widely accepted practice.
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:
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
at the
PrintAgebegin 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.