I’m part of a team of 10 developers, and recently our product team requires us to use feature flags for almost every new change.
The idea is that they can always “roll back” to the previous behavior by turning the flag off.

This leads to our existing Angular/TypeScript code becoming full of if checks, for example:

foo() {
  const dialog = this.featureFlag.has('...') ? dialogX : dialogY;
  dialog.work();
}

bar() { // a very long and old function here..
  ....
  if (this.featureFlag.has('...')) {
    // new code
  } else {
    // old code
  }
  ....
}

As time goes on, the code becomes harder to read and maintain.

Is there a better pattern or approach to handle many feature flags in Angular/TypeScript without cluttering the code with conditionals?

We’re using Angular, and the issue is mainly on the TypeScript side.

3 Replies 3

A possibility could be to use some preprocessor (e.g. GNU m4 or GPP) to generate the TypeScript code.

The set of flags required by your product team will then be the preprocessor options.

You may want to use a builder program (GNU make or ninja, etc...) to run these preprocessing commands.

You certainly should use some version control program (e.g. git) to manage these preprocessing scripts.

in majority of cases if is the most simple tool to use. In addition to that you can use DI to conditionally have providers

 const MY_CONFIRMATION_DIALOG = new InjectionToken<ConfirmationDialog>('Confirmation Dialog', {
        providedIn: 'root',
        factory: () => inject(FeatureFlags).has('dialog2') ? new MyDialog2() : new MyDialog1(),
      });

you can have directives to make it a bit more readable/easier to use in templates

<div *appFeature="'featureX'">
  feature flag content
</div>

if you wish, you could even use DI to conditionally replace application components via DI, But you will have to dynamically render them with component outlet directive. However this way some typescript types verification is lost

That's just the undesired side-effect of using feature flags. A way to make this better you can separate everything from your ifs into some plugin or class where at the start of each function the check is being done. So you repeat the function calls, but not the ifs outside the feature.

However, feature flags are in general a bad idea in my opinion, the desire to release something that is not ready nevertheless. This is why plugins in general were invented. So if you have an unfinished feature you intend to test at production, make a plugin, install the plugin at the places where you wish and your plugin-less code should stay the same.

Your Reply

By clicking “Post Your Reply”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.