Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Type safe" UUIDs?

Tags:

java

We use make heavy usage of java.util.UUID in our projects to identify ojbects and do operations on them like in this interface:

List<UUID> searchPerson(String text);
Person fetchPerson(UUID personUUID);

List<UUID> searchAdress(String text);
Person fetchAdress(UUID adressUUID);

But what can happen now, and is a source of Runtime errors, is that a developer accidently passes a personUUID to the fetchAdress method, which should not happen.

Is there any way to make this kind of "type safe" so hat he can't pass the fetchAdress method a personUUID? Maybe there is a way to do this using generics?

like image 315
Sylar Avatar asked May 21 '26 04:05

Sylar


1 Answers

Build a class that includes UUID functionality by composition, and then subclass it for each individual "type" of UUID you need.

If you don't need/want the full UUID API on your subclasses, you could be extra lazy and just wrap it. Something like this:

public class MyUUID {
    private UUID uuid;
    public MyUUID() {
         uuid = UUID.randomUUID();
    }

    public UUID getUUID() {
        return uuid;
    }
}

public class PersonUUID extends MyUUID { }
public class AddressUUID extends MyUUID { }

If manually unwrapping to get the UUID object out annoys you, just implement the full UUID API on MyUUID and delegate each call to the uuid member.

like image 157
Cory Petosky Avatar answered May 23 '26 22:05

Cory Petosky