Quick revision
The short answer
Use enum Permission with EnumSet in code, because it gives fast checks and type safety, but never persist ordinals or an ordinal-based bit mask: each constant gets an explicit stable code, and the database stores those codes (or the names) in a join table or an array column. Reading code tolerates codes it does not know by ignoring and logging them, and the old int mask is migrated once with an explicit bit-to-permission mapping that is tested bit by bit.
What to remember
In this answer, we kept EnumSet<Permission> for in-memory checks, where it is fast and type-safe, and refused to persist ordinals or ordinal-based masks because inserting or reordering constants silently changes their meaning. We gave each constant a stable code, stored the codes in a join table or array column, ignored and logged unknown codes so older instances survive newer data, and migrated the old mask with an explicit bit mapping tested for every bit, in phases that can be rolled back.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Use enum Permission with EnumSet in code, because it gives fast checks and type safety, but never persist ordinals or an ordinal-based bit mask: each constant gets an explicit stable code, and the database stores those codes (or the names) in a join table or an array column. Reading code tolerates codes it does not know by ignoring and logging them, and the old int mask is migrated once with an explicit bit-to-permission mapping that is tested bit by bit.
Background to this question
Permissions are a place where a quiet data bug turns into a security incident. If a stored value starts meaning a different permission after a deploy, users gain or lose access without anyone noticing. This question looks like a refactoring exercise, but it really tests whether we can separate the in-memory representation, which can be anything fast, from the stored representation, which must keep its meaning across many releases. In this answer, we will look at what is wrong with both the int mask and the Set<String>, see why EnumSet belongs in memory only, design stable codes and a storage schema, handle values written by a newer version, and plan the migration of the existing mask.
1Where the Current Design Hurts
Today the database holds an int bit mask: bit 0 might mean read, bit 1 write, bit 2 delete and so on. The meaning of each bit lives only in code, often in a comment or a list of constants. A mask is compact, but nobody can read it in a query, and there are only 32 bits to spend.
The code side holds Set<String>. Strings are readable but not type-safe: a check like perms.contains("ADMN") compiles and is always false, and nothing tells us which strings are valid. Every service that converts between the mask and the strings has its own copy of the mapping, which is how the two drift apart.
An enum Permission fixes the code side at once. The compiler knows every valid permission, an IDE can find every use of Permission.DELETE, and EnumSet<Permission> makes checks like perms.contains(Permission.DELETE) and perms.containsAll(required) single bit operations.
2Why Ordinals and Ordinal Masks Must Never Be Stored
It is tempting to store the EnumSet the way it already looks inside: as a long of ordinal bits. The trouble is that an ordinal is simply the position of the constant in the source file. Suppose the enum is READ, WRITE, DELETE, and a developer adds EXPORT between READ and WRITE because it reads nicely there.
Nothing fails. No exception is thrown, no test that creates fresh data notices, and every existing user's permissions silently shift. The same thing happens if someone sorts the constants alphabetically or deletes one that seems unused. JPA has the same trap: @Enumerated without arguments defaults to EnumType.ORDINAL, so an entity field mapped that way stores positions. We always write @Enumerated(EnumType.STRING) or use a converter.
So the rule is that the stored form must not depend on the order of declaration. Two forms meet that rule: the constant's name, or an explicit code we declare on the constant.
3Giving Each Constant a Stable Code
Names are readable and work out of the box, but renaming a constant in code then becomes a data migration. Explicit codes separate the two: the Java name can be improved freely, while the code is a contract that never changes once used.
Notice that fromCode returns an Optional instead of throwing, unlike Permission.valueOf, which throws IllegalArgumentException for an unknown name. That choice matters in the next section. A unit test should also assert that every code is unique and that the list of codes only ever grows, so nobody can reuse a retired code for a new meaning.
4Storing the Codes
The cleanest relational form is a join table with one row per user and permission: user_permission(user_id, permission_code) with a primary key on both columns. Queries become readable (which users can export?), a foreign key or a check constraint can restrict codes to a permission table, and there is no limit on how many permissions exist. In PostgreSQL an array column such as permissions text[] on the user row is a reasonable alternative when we always load all permissions together, and a GIN index still makes contains queries fast.
In JPA the join table maps naturally to an element collection with a converter from Permission to its code, and the entity can expose the result as an EnumSet built after loading. Either way, the database holds strings that mean the same thing in every release, and the application turns them into an EnumSet at the boundary.
- Business checks
EnumSet<Permission>:containsAll, one bit operation - Mapping at the boundary
Permission.fromCode/code(), unknown codes logged - Database
user_permission(user_id, permission_code)or text[] - Legacy columnint mask, read only during migration, then dropped
4 layers, from the top down. Step through them one at a time.
Only the middle layer knows both forms, so the stored data never depends on declaration order.
5Reading Codes Written by a Newer Version
During a rolling deploy, old and new instances run side by side. Release 5 adds a permission called export and an admin grants it to someone. An instance still running release 4 then loads that user and meets the code export, which it has never heard of. If loading throws, that user cannot log in on old instances until the deploy finishes, and a rollback would break them completely.
So the reader ignores codes it does not know, logs them once with the user id, and counts them in a metric. For permissions, ignoring is also the safe direction: an unknown permission is simply not granted, so the failure mode is denying access, never granting it. What the reader must never do is map an unknown code to some default permission, and the writer must never rewrite the row without the unknown code, or an old instance would quietly delete a newer grant. That means updates should add or remove individual rows rather than replace the whole set.
6Migrating the Existing Bit Mask
The migration is a one-time mapping from each bit of the old mask to a code. We write the mapping down explicitly, from the legacy code's bit constants, not from the new enum's ordinals, because those are exactly the thing we are moving away from.
The tests cover every bit: for each of the 32 bit positions, a user with only that bit set must end up with exactly the expected code, or the test must prove the bit was never used. We also compare, for every user, the permission set decoded from the old mask with the one read from the new table, and the counts must match before we switch.
In production we run it in phases: write both forms for a release, read the new form while comparing it with the old one and alerting on differences, then stop writing the mask, and only after a safe period drop the column. Each phase can be rolled back on its own.
7Follow-up questions
Why not just store the enum names instead of separate codes?
Names work well and many teams choose them. The cost is that renaming a constant becomes a data migration, and someone eventually renames one without knowing it is persisted. Explicit codes make the contract visible in the code, so a rename of the Java constant is harmless. If we do store names, a test that compares the enum's names with a checked-in list of persisted names catches accidental renames.
Is ignoring unknown permission codes always right?
For permissions, ignoring is safe because it can only deny access, never grant it. For data where losing a value changes behaviour in a dangerous way, such as a set of restrictions or blocks, ignoring would weaken protection, so there we might reject the record or keep the unknown codes and preserve them on write. The direction of failure decides the policy.
Would a bit mask with explicit bit numbers per constant be acceptable?
It avoids the ordinal problem if every constant declares its bit, but it still leaves a value nobody can read in SQL, a hard limit of 32 or 64 permissions, and every reader must agree on the mapping. A join table or array of codes costs a little more storage and is much easier to query and evolve.
8Conclusion
In this answer, we kept EnumSet<Permission> for in-memory checks, where it is fast and type-safe, and refused to persist ordinals or ordinal-based masks because inserting or reordering constants silently changes their meaning. We gave each constant a stable code, stored the codes in a join table or array column, ignored and logged unknown codes so older instances survive newer data, and migrated the old mask with an explicit bit mapping tested for every bit, in phases that can be rolled back.
Open with
I would use enum Permission with EnumSet in code, because checks become type-safe and containsAll is a single bit operation, but I would treat that purely as the in-memory form.
Then, if they want more
The stored form must not depend on declaration order, so I would never persist ordinals or a mask built from ordinals; if someone inserts a constant in the middle or sorts them, every stored value silently shifts.
Instead each constant declares an explicit stable code, and the database stores those codes in a join table, user id plus permission code, or in a text array column in PostgreSQL. If we use JPA, I make sure nothing uses the default ORDINAL enum mapping.
The mapping happens at the boundary with a fromCode method that returns an Optional, so when an older instance reads a code written by a newer release during a rolling deploy, it ignores it, logs it and counts it. For permissions that is the safe direction, because an unknown permission is not granted.
Writes add or remove individual rows so older instances never wipe newer grants. Finally, I migrate the existing int mask with an explicit mapping from each legacy bit to a code, with a test for every bit position, a check that no unmapped bits are set, and a phased rollout with dual writes and comparison before dropping the old column.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- The Collections Framework, overview, java.util, package documentation
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A legacy service stores user permissions as an int bit mask in the database and as...": https://scrivio-interview-library.netlify.app/java/sets/399667ac68/