I often have call hierarchies in that all methods need the same parameters. If I dont't want to put them on the instance level (member of the class) then I ask me always if its meaningfull to check the validity of them in each method.
For example:
public void MethodA(object o){
if(null == o){
throw new ArgumentNullException("o");
}
// Do some thing unrelated to o
MethodB(o);
// Do some thing unrelated to o
}
public void MethodB(object o){
if(null == o){
throw new ArgumentNullException("o");
}
// Do something with o
}
If Method
A uses the parameter, then its clear, I have to check the validity there and also in MethdoB. But as long as MethodA does nothing more with o
than give it to MethodB
, is it good practice to check the validity also in MethodA
.
The avantage of checking also in MethodA
may be that the exception throws in the method the callee has called, that is nice, but is it necessary? The call stack will state this also. Maybe its meaningfull in public,internal,protected but not in private methods?
I took the null-check as an example, but also index-validations or range validations fall in the self question, however I think there are limitations because of the danger of redundant code. What do you think?
UPDATE
Through the answer of AakashM I have seen that I was to little precise. MethodA
not only calls MethodB
, it does also other things but not related to o
. I added an example to clarify this. Thanks AakashM.