Whats the best practice?
function A() {
if (someClassValue > 0) {
B();
}
}
function B() {
...do smth, you expect (someClassValue > 0)...
}
here the coder might forget to check the conditions before calling, and run the system unconsistent…
but from the logical point of view, the caller calls the function, therefore he should be responsible for conditions, when calling a function, on the other hand, its error prone
or
function A() {
B();
}
function B() {
if (someClassValue > 0) {
return;
}
...do smth...
}
this might look missleading from the view of body A
or
function A() {
if (someClassValue > 0) {
B();
}
}
function B() {
if (someClassValue > 0) {
return;
}
...do smth...
}
this is unnecessary double checking
whats the right approach? should a function check the condition to be executed, or should the function that calls this function check the conditions for calling B
Rule: Always validate parameters in all publicly exposed functions.
Corollary: It’s not necessary to validate parameters in any non-publicly exposed functions. This usually has some marginal performance benefit, but it also keeps your code clean and easier to read, especially if you follow otherwise good design patterns and have public-facing functions call down into consolidated private functions to do actual work.
If and only if profiling tells you that parameter validation is a significant bottleneck in your application should you become concerned with minimizing impact points and trimming them out where not absolutely necessary. Alternatively, you could leave them in for debug builds and remove them for release builds, minimizing the performance impact while still fulfilling their basic purpose as sanity checks. But I must say that I’ve never seen a parameter validation that was bottlenecking an application…
As for your question above (which I’ve conveniently ignored), it really doesn’t matter which style you pick, so long as you follow the above rule(s). As is generally the case with questions tagged coding-style, the most important thing is to pick a style and stick with it—consistency is the real winner in the long term.