When to check function / method parameters?

when writing small functions, the case often arises when some parameters are transferred to a function that itself passes them only to small functions in order to serve its purpose.

For example (C # -ish syntax):

public void FunctionA(object param)
{
    DoA(param);
    DoB(param);
    DoC(param);
    // etc.
}

private void DoA(object param)
{
    DoD(param);
}

private void DoD(object param)
{
    // Error if param == null
    param.DoX();
}

Thus, the parameters are not used inside the called function, but "somewhere" in the depths of the small functions that perform the task.

So, when is it better to check if my Object parameter is null?

When checking function A:

Pro: -No overhead is not associated with the use of additional methods, which, in the end, will do nothing, because the object is null.

Con: -My syntactically wonderful FunctionA is polluted with ugly validation code.

When checking only when using a param object:

Pro: - FunctionA :)

: - , , param- null. - , .

+3
6

, , , , DoD(). FunctionA(), , , FunctionB() DoD(). .

+4

, , - DoD, DoA, , . , , , - , .

+6

, , . DoD.

, Bertrand Meyers .

+1

. , , , . , downstream ?

, , , .

+1

:) , , :

public void FunctionA(object param)
{
    assert(param != null && param.canDoX());
    DoA(param);
    DoB(param);
    DoC(param);
    // etc.
}

private void DoA(object param)
{
    assert(param != null && param.canDoX());
    DoD(param);
}

private void DoD(object param)
{
    assert(param != null && param.canDoX());
    if ( param != null )
        param.DoX();
    else
        // Signal error, for instance by throwing a runtime exception
        // This error-handling is then verified by a unit test that 
        // uses a release build of the code.
}

To eliminate this, the obvious solution is to deploy a check to a separate validator function. Using a C-style preprocessor or just sticking to statements, it should be trivial for this “paranoid” check to be excluded from releases.

0
source

The caller has a duty to pass a valid parameter. In this case:

if(param != null)
{
  FunctionA(param);
}
0
source

Source: https://habr.com/ru/post/1709295/


All Articles