DEV Community

Discussion on: Bitmasks: A very esoteric (and impractical) way of managing booleans

Collapse
 
bajix profile image
Thomas Sieverding

I absolutely love working with bitmasks! They pair incredibly well with MongoDB: there are query expressions for $bitsAllSet/$bitsAnySet + $bitsAllClear/$bitsAnyClear to make for some very succinct and expressive queries, and then there also $bit update operators for setting/unsetting bits. Field selection is a lot more straightforward; it indexes well, especially w/ compound indexes; and it just feels clean. I've found that a lot of queries are just much easier to express like this, for instance:

let cursor = Users.find({
  status: {
    $bitsAllSet: VERIFIED | FEATURED,
    $bitsAllClear: BANNED | DISABLED | PROVISIONAL
  }
}).lean().cursor();

Also, there are a lot of times in which logical expressions are much cleaner with bitmasks. For instance, say you wanted to update a doc and wanted to trigger some behavior based off of the changes; the optimal way to do this IMO is to use a findOneAndUpdate with bitwise updates ($bit) and then to return the old doc / sync the bitwise updates and to compute the XOR. Once you have the XOR of the update, it's really easy to derive events: IE status & XOR & VERIFIED -> they are verified & they weren't verified before this update. The most powerful use case I've found is for shared documents, where you have a subdocument array for user data w/ an ObjectID ref + a bitmask, and then you can use $elemMatch updates to set each users respective flags, and then you can do awesome things like taking the AND of each users flags + the XOR of an update as to derive events based of when flags are mutually set by both users and became such as a result of this update. This very simple design pattern works for a staggering number of use cases.

Collapse
 
somedood profile image
Basti Ortiz

Ayyyyy. I can't disagree with your level of enthusiasm! Bitmasks are definitely great for these kinds of use cases. As long as the code for these design patterns are relatively straightforward and easy to fathom, bitmasks aren't really as "bad" and "esoteric" as I have made them to seem like in the article.