Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should Model Objects Have Interfaces?

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?

like image 549
sma Avatar asked Mar 09 '10 22:03

sma


People also ask

Does a model need an interface?

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.

Should domain objects have interfaces?

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.

Should a class always have an interface?

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.

Do we need to create object interface?

No, you cannot instantiate an interface. Generally, it contains abstract methods (except default and static methods introduced in Java8), which are incomplete.


2 Answers

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)

like image 165
David Avatar answered Sep 22 '22 22:09

David


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.

like image 41
Roman Avatar answered Sep 18 '22 22:09

Roman