Search code examples
matlabarguments

How to custumize code suggestion for argument validation functions


I am trying to use argument validation to require that an input is a member of a predefined list of strings, which can be done using the mustBeMember function (see below). As expected, this throws an error if the user does not enter a valid argument, and additionally, code suggestion shows the user a list of the possible options when the user is typing out the function.

function out = myFunc1(arg)
    arguments
        arg {mustBeMember(arg, ["opt1", "opt2", "opt3"])};
    end
    out = arg;
end

The problem is that I have many different functions that all use the same list of strings, so I have to copy and paste the list, which is unmaintainable. So I created a custom, reusable validation function that contains the list internally (see below).

function out = myFunc1(arg)
    arguments
        arg {mustBeValidOption};
    end
    out = arg;
end

function mustBeValidOption(arg)
    try
        mustBeMember(arg, ["opt1", "opt2", "opt3"]);
    catch ME
        throwAsCaller(ME);
    end
end

Now I can use the mustBeValidOption validator in multiple functions. However, code suggestion no longer is functional.

So this is my question: How can I customize code suggestion for argument validation functions? Alternatively, is there a way to have the member list that is passed into the "mustBeMember" validator come from a separate file?


Solution

  • I think your best bet here is to use an enumeration as the argument type. (You could use "functionSignatures.json"... but I think that would end up being more duplication). For example:

    % ValEnum.m - enumeration of allowed options
    classdef ValEnum
        enumeration
            opt1
            opt2
            opt3
        end
    end
    
    function out = fcn1(arg, thing)
        arguments
            arg (1,1) double
            thing (1,1) ValEnum
        end
        out = string(arg) + ":fcn1:" + string(thing);
    end
    

    Here's what happened after I typed "fcn1(3, Tab":

    Shows tab completion of fcn