Reputation: 10210
I was told never to assume validity with regards to incoming data (in reference to user input - which I always validate), however, is there any reason to take the same approach with parameters being passed between object methods?
When performing actions on method parameters, should I always validate them even if I am 99.9% certain the incoming parameters will have valid data?
Upvotes: 2
Views: 249
Reputation: 3592
At least you should validate parameters from public methods in boundaries layers (eg Facades). In other cases you should consider if your parameters need to be validated. Another hotspot is persistence, i recomend you to validate parameters in persistence methods.
Upvotes: 0
Reputation: 6032
It Depends.
You should only validate when there is a possibility for the inputs to be invalid, such as public methods in libraries, methods that work on user input, etc.
The methods that do not validate should be shielded from the user, either through the façade design pattern or an additional layer.
Validating the same things over and over again will increase the risk of errors when maintaining the code, not provide much additional safety and increase the size of the code base.
Upvotes: 2
Reputation: 4094
Normally, that is where I would use an
assert
statement if the language of choice offers that. The advantage is that you express the pre/postcondiations of the parameters, they serve as comments for future developers and can be normally toggled by a flag to the compiler/interpreter to not let the code blow up as a result of a assert error.
In computer programming, an assertion is a predicate (a true–false statement) placed in a program to indicate that the developer thinks that the predicate is always true at that place. - Wiki about assertions
Upvotes: 1