views:

29

answers:

2

If you have a chain of functions that operate on some data, is it better to have each function verify the data is valid before using it, or do that verification at the start of the chain and have every function in the chain just "trust" that it is valid?

A: 

Depending on whether the lower functions on the chain are called by themselves will largely influence your decision. If you have a rigidly tiered system with certain classes only being called by other classes of your program, those inner classes can have much lighter data checking and "trust" the data.

From "Code Complete 2" by Steve McConnell:

"One way to barricade for defensive programming purposes is to designate certain interfaces as boundaries to 'safe' areas. Check data crossing the boundaries of a safe area for validity and respond sensibly if the data isn't valid.

The same approach can be used at the class level. The class's public methods assume the data is unsafe...Once the data has been accepted by the class's public methods, the class's private methods can assume the data is safe."

Peter Anselmo
+1  A: 

Is always a good practice to apply defensive programming. You should contemplate all possible scenarios.

The validation gets extremely important if the input comes from an user, in that case you must make sure that your code knows what to do in each invalid data scenario. Try assertions for the situations you can predict and exceptions for the unpredictable ones, the details would depend on the language you're using. This is the foundation of a bulletproof program.

jromero