I will explain my question by way of example, but I'd love a general solution.
I am writing a JavaScript application that needs to function differently depending on its run-time context. To handle this, I have have done the following. (1) At the beginning of the program, I set two context variables—let's say is_foo
and is_bar
, which can't both be true. Then (2) throughout the code, I check these variables whenever I need to account for the context:
if (is_foo) {
app.do_something(is_foo_config);
} else if (is_bar) {
app.do_something(is_bar_config);
}
Are there any good design patterns or best practices for designing a program that has a "mode" with related configurations?
Best Answer
Generally, instead of setting a flag, you want to use polymorphism to choose between different implementations. In other words, instead of checking
is_foo
all over the place, do it once at the start, like:Alternately, if only the config is different, do something like this at the start:
This lets you later just do:
Basically, by doing the
if
statement once, you minimize the possibility of accidentally forgetting to do it at some later point, and usually also eliminates a lot of repetition.