What are feature flags?
Features flags (aka feature bits, feature toggles) are a very useful technique for managing latent functionality within your application. You expose switches in your application which configure whether certain behavior is enabled or disabled. Typically your would use this pattern for functionality which is under active development and is not ‘fully baked’.
There are various classes of behavior which you might expose toggles for. Common use cases include hiding user-facing features which are still in development, or switching whether your code uses a new version of a third-party service. This allows you to do branch-by-abstraction and therefore avoid long-lived feature branches which can often be the source of considerable pain to a development team.
For a more in-depth discussion on this pattern, Martin Fowler has a nice writeup. My former colleague Erik Sowa also has a nice presentation describing how we applied ‘feature bits’ at a previous company I worked in. Derek Hammer has a really nice write up on the broader range of patterns available for isolating code when practicing Continous Delivery.
step 1: extracting feature flags from the query string
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
Here we do some simple parsing of
step 2: expose feature flags as classes in the DOM
1 2 3 4 5
Here we use jQuery to register a function on document ready. This function will grab all the feature flags specified in the query params and then add a class to the doc’s
<html> element for each flag, prepended with ‘ff-’ to avoid any naming collisions with other CSS classes.
step 4: show or hide UI elements with CSS
Our goal here is to control whether or not a feature is exposed to an end user. A lot of the time we can hide a feature by simply applying a
display:none the right DOM element. Because we added our feature flag classes to the root
<html> element we can apply simple CSS rules like the following:
1 2 3 4 5 6 7
This will hide the
search-wrapper element (and anything inside of it) by default, but will show it if there is a parent with a class of
ff=search when loading the page. There we have it, a simple feature-flag.
This simple approach works quite nicely for a single-page app (which is what our team was developing), but it does have some issues in other cases. The main problem is that any feature flag you specify in a query param will be lost whenever you leave the current page. This could be remedied by storing feature flags in a cookie or in HTML5 local storage. You’d then check for flags in that store in addition to in the query param during page load. Presumably a flag specified in a query param would override anything in the store.