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
Redundant code isn't the most elegant but its safe.
This depends on who your intended user is, if its you then your in control of how everything is used and the checks are only necessary if your unsure of what the state of your variables will be.
If your making this for someone else to use then null checks are probably a good idea. Even if you just throw a NullPointerException its better to fast fail.
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
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.
Definitely check in PrintAge
, it's a right place to check. It can be redundant but won't hurt anyone unless you execute it 1000 times per second. (Depending on the check throw an exception or fix it if you can)
Other check is depend on your actual flow, in this example you don't have a flow so I can't comment on that bit. But generally consider your parameters as tainted.
There is only one occasion that a constructor can return null [new()
on a Nullable<T>
] - so the calling code doesn't need to check.
The callee probably should check; throwing an ArgumentNullException
if it was null. In .NET 4.0 this will be better served by code contracts. But not yet ;-p
I prefer null checks inside methods for two reasons.
I think functions should be 'complete', ie handle null values/'edge cases' and not rely on callers. This is for two reasons,
having null checks inside the method reduces overall number of null checks inside the code, which usually means more readable code
As I understand your question it is more general than illustrated by your example. My preferences are as follows:
Brad Abrams has some more input here: http://blogs.msdn.com/brada/archive/2004/07/11/180315.aspx