As a good practice, do you think one should verify passed parameters within a function to which the parameters are being passed, or simply make sure the function will always accept correct parameters?
Consider the following code:
Matrix * add_matrices(const Matrix * left, const Matrix * right)
{
    assert(left->rowsCount == right->rowsCount
        && left->colsCount == right->colsCount);
    int rowsCount = left->rowsCount;
    int colsCount = left->colsCount;
    Matrix * matOut = create_matrix(rowsCount, colsCount);
    int i = 0;
    int j = 0;
    for (i; i < rowsCount; ++i)
    {
        for (j; j < colsCount; ++j)
        {
            matOut->matrix[i][j] = left->matrix[i][j] + right->matrix[i][j];
        }
    }
    return matOut;
}
Do you think I should check the parameters before passing them to the function or after, ie. in the function? What is a better practice or is it programmer dependant?
Inside. The function can be viewed as an individual component. Its author is best placed to define any preconditions and check them. Checking them outside presupposes the caller knows the preconditions which may not be the case.
Also by placing them inside the function you're assured every call is checked.
You should also check any post-conditions before leaving the function.
For example if you have a function called int assertValid(const Matrix*matrix) that checks integrity of the object (e.g. the data is not a NULL pointer) you could call it on entry to all functions and before returning from functions that modify a Matrix.
Consistent use of pre- and post- condition integrity are an enormously effective way of ensuring quality and localising faults.
In practice zealous conformance to this rule usually results in unacceptable performance. The assert() macro or a similar conditional compilation construct is a great asset. See <assert.h>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With