Search code examples
functionverification

Is it better to do verification of data at every level that it is used?


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?


Solution

  • 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."