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.
See Question&Answers more detail:os