6

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?

  • Is it possible for the mode to change while the application is running, or is it set once on startup? – FrustratedWithFormsDesigner Nov 5 '14 at 22:23
  • @FrustratedWithFormsDesigner, it is set once at startup. – gwg Nov 5 '14 at 22:25
12

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.

9

Since the mode is selected at startup1 the Strategy pattern would work.

Related is the Replace Conditional with Polymorphism (also here) and Replace Type Code with State/Strategy refactoring.

enter image description here

1 If the mode were changing during the course of execution, then the State pattern would be called for. It's similar to the Strategy pattern and has similar inner workings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.