Should validation be done in functions or when calling the function?

279 views Asked by At

I am making a MATLAB GUI in GUIDE and need to validate parameters that I pass into several functions.

Should the parameter validation be done in the button/slider/edit callbacks or in the function itself?

1

There are 1 answers

0
AudioBubble On BEST ANSWER

Validating arguments in every function (callback or regular) is robust—I'd recommend it every time a function cannot trust its input. The minimal slow down of the function calls due to checking the argument type, size and value pays off in the end, because everybody will understand what the function requires. And the function can be reused independently of the GUI. But sometime it requires stuff like:

if ~isnumeric(x) ...
|| ~isscalar(x)  ...
|| ~isfinite(x)  ...
|| (x <= 0)      ...
|| (x ~= fix(x))
        error('Positive finite integer value required.');
end

and that looks pretty only to few programmers.

On the other hand, the callback deals directly with the edit field, which means that is first to know what might be wrong with the value. If the user doesn't mind to check the error messages in the command window, then don't test the value in the callback. On the other hand, if you want to warn the user about a field being wrong and needing editing, you need to check the edit field value before converting it and sending it as argument to your function.

One might say: why not check the arguments only in the callback function? One possible answer would be because the callback knows only about its value. If two edit boxes hold a min and a max value, each one can check its own value (numeric, scalar, finite), but the necessary relation between a min and a max (max ≥ min) can be tested only the two values are passed to the function that will use those values.