I am creating the domain model in my system. When designing my model objects, should I make interfaces for each entity object? People have told me that our web tier should not care about the implementation of an entity and we should be able to swap out implementations, but I'm not sure that would ever happen.
For example, if we have a Teacher class that maintains a List of Students, the getStudents method could either be:
public List<Student> getStudents() {
return this.students;
}
or this:
public List<Student> getStudents() {
return someExternalService.retrieveStudents();
}
I understand this benefit, but what is the general practice?
But the format and type of data object expected does not change, no matter how you create this object. Therefore model objects which carry the state would not need an interface, but service classes to create and load these model objects needs the interface.
Show activity on this post. My feeling on this is that domain objects (not domain entities, as that title implies something to do with a database) should not be interfaces unless you have a very compelling reason to believe that you will need to support multiple implementations at some point in the future.
When discussing these principles in the book, I regularly encourage the reader to add more interfaces to their classes, to make the overall design of the package or application more flexible. However, not every class needs an interface, and not every interface makes sense.
No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete.
Unless you have good reason to think you will need to swap-out the model I wouldn't worry about it yet. Based on the YAGNI principle (You ain't gonna need it)
None of the projects I've ever seen or participated in had interfaces for domain entities.
But in one of my projects I had interface NamedEntity
:
public interface NamedEntity {
int getId ();
String getName ();
}
All domain entities implemented this interface. It gave me a possibility not to create different jsf converters for different entities but create one converter which used this interface instead of concrete domain classes.
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