I was wondering what was the best practices in terms of collection of resource ID of different types.

My software has a service for each resource, each of this resource has a unique id (hexadecimal like 3dbea72) of their type.

  • tomato
  • potato
  • carrot

I want to create a new service to manage a basket of those resources.

The obvious solution would be to send a the ID along the type

getTomatos() -> [{id: "3dea72", ...}, {id: "3dea73", ...}, ...]
getCarrots() -> [{id: "aaaaa2", ...}, {id: "aaaaa3", ...}, ...]
submitBasket([{type: "tomato", id: "3dbea72"}, {type: "carrot", id: "aaaaa2"}])

But I'm not particularly fan of this solution, so I was thinking to something more optimized maybe.

Generate a unique self-describing ID returned to the client where the first byte describes the type and the next bytes the ID.

013dea72 of the tomato id 3dea72
02aaaaa2 of the carrot id aaaaa2

For the client, the interface

getTomatos() -> [{id: "013dea72", ...}, {id: "013dea73", ...}, ...]
getCarrots() -> [{id: "02aaaaa2", ...}, {id: "02aaaaa3", ...}, ...]
submitBasket(["013dbea72", "02aaaaa2"])

The question is more about the best practices for this usecase, if there is any other solution to solve this problem, what are the cons and pron of those two solutions.



Your first solution is actually the ideal solution for several reasons.

  1. It properly encapsulates an abstraction. This is good API design whether you are building a web service or class library.

  2. Inferring types from Ids is not obvious from the perspective of a human observer. It increases the mental effort required to understand something that is already abstract.

  3. Passing an explicit "type" parameter gives server side code a way to change behavior based on this value, and can be combined with the Factory Pattern to facilitate polymorphism in object oriented languages.

There are valid use cases for composing an Id in this manner, but they are usually driven by very old and well known company policies, public policy or laws (like license plate numbers in the United States).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.