In my application I need to have access some "relational" data at runtime. If I had a lot of data or it changed often I'd store it in a DB (sqlite or something). But I only have a couple of entities with 5-50 objects that won't change (often) and will be changed by the developers alone. So I think it makes sense to simply hard-code the data in Java classes for simpler code maintanence.
All of the entities share a common abstract superclass (having an int id
and a String name
).
After defining the data I'd like to have a reference to each entity object AND to a Collection/Array all of these objects being available outside of the classes.
I want to make sure that the data is immutable.
The first idea was to do something like this:
public abstract class AbstractEntity{
private final int id;
private String name;
protected AbstractEntity(int id, String name){
this.id = id;
this.name = name;
}
private void someMethods(){
...
}
abstract protected void someAbstractMethods(){
...
}
}
public final class MyEntity extends AbstractEntity{
public static final ENTITY_1 = new MyEntity(1, "Entity 1", "foo");
public static final ENTITY_2 = new MyEntity(2, "Entity 2", "bar");
public static final ENTITY_3 = new MyEntity(3, "Entity 3", "baz");
public static final Set<MyEntity> ALL = Collections.unmodifiableSet(new TreeSet<>(Arrays.asList(ENTITY_1, ENTITY_2, ENTITY_3)));
private final String foo;
private MyEntity(int id, String name, String foo){
super(id, name);
this.foo = foo;
}
}
The flaw I see is that when adding a new entity during development I have to add it to the ALL Set as well. That annoys me. It's a kind of redundancy and source for bugs.
I then just thought of using enums as entity classes where I can define the entitiy objects and implicitely have alle of the objects references in the values() Array. But this doesn't work because of having a base class (AbstractEntity) and multiple inheritance not being possible in Java.
The next idea that instead of an abstract base class was to use an interface with default methods and as entities define an enum implementing this interface. But then I wouldn't be able to define int id and String name in the base class (interface) and would have to define it in each subclass.
Is there some syntactic sugar I'm missing? What's the best practice here?