Is there any design pattern or clean way to do function/method parameter checking (against allowed values)?
Currently, lots of the initial code in my functions consists of these parameter checks (empty strings, invalid characters, existing id, ...) and, while necessary, it is a bit ugly and obfuscates the 'real' code of the function. Typically, my code goes something like this:
def my_function(p1,p2,p3,p4):
#check parameters
if p1 == ''
raise InvalidArgError('p1 can not be empty')
if p1 not in valid_list:
raise InvalidArgError('p1 does not exist')
if p2 < 0:
raise InvalidArgError('p2 can not be negative')
...
#finally do something
p = p2+p3
For the solution, I am thinking along the lines of decorators in Python.
I am using Python, although I guess a good solution would be language-independent.
Use the keyword def to declare the function and follow this up with the function name. Add parameters to the function: they should be within the parentheses of the function. End your line with a colon. Add statements that the functions should execute.
Is it good practice to pass a function as a parameter? Passing a private function to someone else because you specifically want them to call it in the way they document for that parameter, is absolutely fine.
The only fairly language independent thing I can imagine at the moment is some kind of code contract so you can do things like:
func foo(param1, param2)
{
Contract.NotNull(param1)
Contract.IsIn(0, 100, param2)
}
I assume you could come up with an implementation of some sorts in most programming languages.
Update
Microsoft is working on an implementation and there is a Java implementation.
Each parameter of a method represents an entity. There must be some constraints or assumptions about the argument values based on which the method/the whole class works. So I write methods for validity check of those parameters.
void drawRectangle(int length, int width) {
if (isValidLength(length) == false || isValidWidth(width) == false) {
// log about invalid argument so that it can be easily traced for debugging
return;
}
// remaining code
}
boolean isValidLength(int length) {
if (value < 0 || value > 100) {
return false;
}
return true;
}
The advantage is avoiding duplicate code. If null checking, range checking is done for the same parameter type in several methods and sometime later the range for that parameter changes due to requirements modification, then changes are to be made in several places. On the other hand, if the check is done in a separate method, scope of change reduces.
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