TechnicalQuestion How to limit argument validation function visibility?
In Function.m I have
function Function(a)argumentsa (1,1) double {Validator(a)}
endprintValue(a);end
function Validator(a)arguments
a (1,1) doubleendif mod(a,7)error("Invalid argument.");
end
end
function printValue(a)disp(a);end
I want to further restrict the visibility of Validator such that it can be called only by Function. I tried to make Validator a nested function of Function, but MATLAB throws me the error "calling nested functions is not supported in arguments blocks". So how do I restrict Validator to be called only in Function and not in other local functions from Function.m (like printValue)?
Edit: sorry for formatting, but Reddit ignores spaces when I write code.
2
u/aluvus 11d ago edited 11d ago
Your code works fine in 24b. However, it also does not contain any nested functions.
Nested functions are declared inside another function. If you move the end that closes Function (that is, the end after printValue(a);) to the very end of the file, now Validator and printValue will be nested functions. And indeed, in 24b you would get that error.
So the solution is to not use nested functions for this. What you want instead are local functions, which come after you have closed the main function in a file.
Turns out that the placement of that end can be very important :)
2
u/aluvus 11d ago
You can post formatted code to Reddit by starting each line with 4 spaces. You can conveniently add the spaces in the Matlab editor by selecting the text and pressing
tabto indent it once.Works:
function FunctionWorks(a) arguments a (1,1) double {Validator(a)} end printValue(a); end % <---- this is the end of FunctionWorks function Validator(a) % local function arguments a (1,1) double end if mod(a,7) error("Invalid argument."); end end function printValue(a) % local function disp(a); endThrows error:
function FunctionFails(a) arguments a (1,1) double {Validator(a)} % Matlab mad about this line end printValue(a); function Validator(a) % nested function arguments % Matlab mad about this line also a (1,1) double end if mod(a,7) error("Invalid argument."); end end function printValue(a) % nested function disp(a); end end % <---- this is the end of FunctionFails
1
3
u/pbrdizzle 15d ago
What you have there looks like it would work for me. Validator is a local function so only visible to other functions in the file. Personally I've found it's good to follow the MW naming convention and reuse validators whenever possible. This is a contrived example but I'd make a normal function