That's a nice id
Another day where a bug was because the wrong id was being passed somewhere. This time it didn't make it onto production. I caught it due to a unit test I wrote. But it did take unnecessarily long to find out.
Fuelled by that distaste, comes today's post where I give you tips that I think improve the developer experience when working with ids.
#1: prefix the entity type
Ever had an id in front of you and you weren't necessarily sure which database table it belonged to? That won't happen anymore if you prefix them. If user ids start with “user_” and profile ids with “profile_” you’ll thank yourself over and over again in the future.
#2: use a time-sorteable string
It's not meaningful most of the time, but you can have a time-sorteable string without centralizarion or delegating it to the database. You can use ksuid or uuid v7. For any of them, if you sort the strings, you also get them time-ordered.
#3: let the type-system help you
If you are using a statically typed language, then you can have different types (classes, interfaces, etc) for different ids. Then your functions receive and return `UserId` and the compiler complains if you try to give it a `CatId`. It's not bulletproof but most of these errors happen at the layers with business logic and not the ones concerning serialization.
If the boilerplate of creating a bunch of types bothers you there's always the option of creating a single generic one, `EntityId<T>`. Then your functions use `EntityId<User>` or `EntityId<Cat>`. It achieves the same type-safety.
Obviously we’re not creating new systems all the time and migrations can be painful, but hopefully you have a chance of using one of these in the future and save yourself some precious debugging time.