Design Patterns – Best Practices for Multi-Mode Software

design-patterns

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:

if (is_foo) {
  app = new FooApp();
} else {
  app = new BarApp();
}

Alternately, if only the config is different, do something like this at the start:

if (is_foo) {
  config = is_foo_config;
} else {
  config = is_bar_config;
}

This lets you later just do:

app.do_something(config);

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.

Related Topic