Should Model Objects Have Interfaces?

12,402

Solution 1

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)

Solution 2

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.

Solution 3

I can't speak to general practice, but it is hardly just about hiding the implementation.

It's about formalizing the interface as the basis for documentation and contracts.

In abstracting your models out into interfaces, you are creating documentation for service client developers. Depending on your development style, you may or may not already have a formal description of your service (e.g., a WSDL-based description). Interfaces can fill that need.

Solution 4

I think there is an important difference between having interface for service to retrieve the object and the model object itself.

At runtime the service to load a model object can differ based on from where you are requesting the data. 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.

The only reason for model objects to have interfaces would make sense if model object is not just a simple bean type of object but object which exposes some kind of behavior as well.

Share:
12,402
sma
Author by

sma

Updated on July 10, 2022

Comments

  • sma
    sma almost 2 years

    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?