The issue at hand
I am facing a challenge with a method foo(msg: string, arg: string)
. This method calls another method from the object bar
, located within the same class as foo
. The specific method to be called is determined by the value of arg
. I am looking for a suitable solution to tackle this problem effectively.
In my actual codebase, I plan to use this for refactoring purposes. The snippet looks like this:
add() { foo('Adding', 'add'); }
sub() { foo('Subtracting', 'sub'); }
mul() { foo('Multiplying', 'mul'); }
div() { foo('Dividing', 'div'); }
My proposed solution
My current approach involves a method structured like this:
foo(msg: string, arg: string) {
console.log(msg);
this.bar[arg]();
// Additional code here
}
In essence, I aim to invoke the method indicated by arg
on bar
. This implementation functions correctly. However, I wish to constrain the possible values that arg
can assume. One potential strategy could be:
foo(arg: string) {
if(arg !== 'fun1' && arg !== 'fun2') {
// Manage error scenario
}
this.bar[arg]();
}
The argument arg
will always be static. I directly specify constant values every time, such as
foo('fun1');
and never utilize something akin to
// Demonstrative usage I want to avoid
let arg = someFunctionReturningAString();
foo(arg);
My concerns primarily revolve around 1) ensuring robustness and avoiding criticism for adopting unsound practices, and 2) facilitating spelling error detection by IDE tools through a more optimal approach.
Hence, my objective revolves around devising a user-friendly mechanism for invoking a method from bar
based on the parameter arg
. Ideally, this would enable improved spell-checking capabilities within an IDE. How should I proceed?