Search code examples
javadesign-patternstype-safety

Design patterns for type-safe integers?


I have an application that works with a entities that all have an integer ___ID primary key (e.g. StudentID, CourseID...etc)

I want to add a bit of type safety to the program, so for example a function that takes as input a StudentID, cannot be accidentally passed a CourseID.

First idea that came to my mind is to create simple empty classes like this:

public class StudentID extends java.util.Integer {}
public class CourseID extends java.util.Integer {}

This doesn't work since java.util.Integer is final and can't be extended.

Second idea is to have a data class that only holds an integer:

public class StudentID {
    private final int id;
    public int get() { return id; }
}

Though it would be a lot of boilerplate code.

Third idea is like second idea but to save on boilerplate code by having one base class that defines the get method and empty classes that inherit from it:

public abstract class AbstractID {
    private final int id;
    public int get() { return id; }
}

public class StudentID extends AbstractID{};
public class CourseID extends AbstractID{};

Are there any other/better known patterns for this problem?


Solution

  • How about ID<T>? If you want to restrict some argument to a function, I think you can do as following:

    void foo (ID<? extends Student> param);