Genadinik Genadinik - 25 days ago 9
Java Question

Java - should I represent user ids with int, long or Integer?

When I need to do numerical comparisons of user ids, should I do something like:

int numeric_user_id = Integer.valueOf("1234343");

or is it better to put that into a long, or keep it an Integer?


Answer Source

Unique Identifiers should not carry any special semantic meaning; ever. UUID or GUID types were designed just for entity identifiers, so that you don't infer any semantic meaning to them, that is what makes them opaque.

One of many practical benefits is that they will never clash when importing and exporting data to different databases, ie; development, qa, production, or when used in a cluster. If you use plain old numbers, especially auto-incrementing numbers, each database will have a different user for the same number and it is next to impossible to keep out dupes and other bad data from creeping into the different systems. UUID/GUID solutions completely avoid this kind of problem.

There are lots of reasons not to use the id for anything other than ids. What happens when you have more than 30000 beta users, what happens when you want to kick some people out of the beta user program, what happens when ... ?

As for using ids for business logic like identifying beta users, don't use the id for that, use another attribute flag to identify them. You could have a boolean flag, or an enum or some other flag, or even combine the fact that they are a beta user with when they joined the beta program by having a nullable timestamp, that would flag them as such, but that could end up being less flexible by leaking concerns; but it may be appropriate in some cases.

public interface Identifiable {

    public UUID getUUID();

public interface BetaUser extends Identifiable {

    public boolean isBetaUser();
    public Date    joinedBetaProgramOn();

int, long, and other number types should only be used for math; not for identity management or business logic un-related to mathematical concerns.

if you want to get the nth user of the system, then sort them by join date and take their index from the list