Search code examples
javaentityimplementation

Should the Entity class implements interface?


I have my Entity classes and I want to represent them with graphic. In my realisation, I have Drawable interface and classes which implement this interface for each Entity. As for me it is obviously that entities should implement Drawable interface, but I hear from experienced developers that this is a bad practice. I little bit confused because JavaDoc says:

Entities may extend both entity and non-entity classes, and non-entity classes may extend entity classes.


Solution

  • This is very much opinion based (hence the close vote), but let's see if we can get some discussion going. Let's consider your proposition:

    I want my entity classes to implement an interface that has nothing to do with persistence

    Pros:

    • Less duplication of class hierarchy. If something changes in the database, you might be able to have the program work as usual, or with only minor changes
    • Flatter class hierarchy. You'll be able to visualize your data without a layer translating it to your Drawable objects

    Cons:

    • Entities are just data, and should not be responsible for drawing themselves. They should be transformed into domain objects first
    • Passing entities into other layers of the system can cause bugs, when they're treated by code as domain objects