In a simplified example, yes, perhaps the second format is preferable.
However, this does not apply to larger, more complex and more realistic programs.
Since you never know in advance where and how "foo" will be used, you need to protect foo by checking the input. If the input is verified by the caller (for example, "main" in your example), then "main" must know the verification rules and apply them.
In real programming, input validation rules can be quite complex. It is not necessary for the caller to know all the validation rules and apply them correctly. Some subscriber somewhere forgets the verification rules or does the wrong ones. Therefore, it is better to check the validity inside "foo", even if it is called again. This transfers the load from the caller to the called party, which frees the caller to think less about the details of "foo" and use it more like an abstract, reliable interface.
If you really have a template where "foo" will be called several times with the same input, I suggest a wrapper function that performs the check once, and an unprotected version that performs the check:
void RepeatFoo(int bar, int repeatCount) { /* Validate bar */ if (bar != /*condition*/) { //code, assert, return, etc. } for(int i=0; i<repeatCount; ++i) { UnprotectedFoo(bar); } } void UnprotectedFoo(int bar) { /* Note: no validation */ /* do something with bar */ } void Foo(int bar) { /* Validate bar */ /* either do the work, or call UnprotectedFoo */ }
abelenky
source share