Where is the best place to validate input parameters of function: in caller or in function itself?
As I would like to improve my coding style, I try to find the best practices or some rules for this issue. When and what is better.
In my previous projects, we used to check and treat every input parameter inside the function, (for example if it is not null). Now, I have read here in some answers and also in Pragmatic Programmer book, that the validation of input parameter is responsibility of caller.
So it means, that I should validate the input parameters before calling of the function. Everywhere the function is called. And that raises one question: doesn't it create a duplication of checking condition everywhere the function is called?
I am not interested just in null conditions, but in validation of any input variables (negative value to
sqrt function, divide by zero, wrong combination of state and ZIP code, or anything else)
Are there some rules how to decide where to check the input condition?
I am thinking about some arguments:
- when the treating of invalid variable can vary, is good to validate it in caller side (e.g
sqrt()function - in some case I may want to work with complex number, so I treat the condition in caller)
- when the check condition is the same in every caller, it is better to check it inside the function, to avoid duplications
- validation of input parameter in caller takes place only one before calling of many functions with this parameter. Therefore the validation of a parameter in each function is not effective
- the right solution depends on the particular case
I hope this question is not duplicate of any other, I searched for this issue and I found similar questions but they don't mention exactly this case.