You can remove the option value checking from your function's body by testing the option values in the pattern match of the function call. This method allows your function's body to leave out testing for valid options which will simplify the code; which is very handy as function complexity increases.
ClearAll[myfit];
Options[myfit] = {Method -> "Linear"};
myfit[data_, opts : OptionsPattern[]] /;
MemberQ[
{"Linear", "Quadratic"},
Method /. FilterRules[Append[{opts}, Options[myfit]], Method]
] :=
Switch[OptionValue[Method], "Linear", t, "Quadratic", t^2]
then
myfit[{1}]
(* t *)
myfit[{1}, Method -> "Quadratic"]
(* t^2 *)
myfit[{1}, Method -> "Cubic"]
(* myfit[{1}, Method -> "Cubic"] *)
The MemberQ
checks if the Method
option is valid. The defaults are Append
ed to the provided options (opts
) because the particular option may not have been provided and we need success in that case. FilterRules
picks out rules with matching keys. Since provided options come before the defaults in the list of filtered rules ReplaceAll
(/.
) will pick the provided option instead of the appended default in the case an option is provided. Finally, MemberQ
test if the option value is a member of the allowed list.
To test more than one option multiple MemberQ
's can be And
ed together in the pattern test.
Hope this helps.
Extension
Create a checkOptionValue
function for multiple option checks.
ClearAll[checkOptionValue];
SetAttributes[checkOptionValue, HoldAll];
checkOptionValue[f_Symbol, opt_, optValues_List, opts : OptionsPattern[]] :=
MemberQ[optValues, opt /. FilterRules[Append[{opts}, Options[f]], opt]]
Then use for multiple option checks.
ClearAll[myfit];
Options[myfit] = {Method -> "Linear", Background -> Green};
myfit[data_, opts : OptionsPattern[]] /;
checkOptionValue[myfit, Method, {"Linear", "Quadratic"}, opts] &&
checkOptionValue[myfit, Background, {Green, Purple}, opts] :=
Panel[Switch[OptionValue[Method], "Linear", t, "Quadratic", t^2],
Background -> OptionValue[Background]]
Which gives
If[]
?$\phantom{}$ $\endgroup$