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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With