简体   繁体   中英

Hierarchy of interfaces

Is it considered bad to create a hierarchy of interfaces in Java?

I have designed my repository layer like this:

  • Repository , contains CRUD methods
  • JPARepository , potential methods that is only needed in JPA
  • SomeModelRepository , specific methods for the repository of that model.
  • SomeModelJPARepository , extends JPARepository AND SomeModelRepository

Is this considered bad practice, and is it a strange organized hierarchy?

No, in fact it's fairly common to create interface hierarchies, at least in libraries. Take NavigableSet for instance, which has 4 layers of interfaces above it (SortedSet, Set, Collection, Iterable).

In this example, the diamond inheritance is a bit peculiar, but if necessary not a bad choice per se. But usually a tree hierarchy is much clearer and better. In this case I would consider making either:

  1. SomeModelRepository a subclass of JPARepository, thus forcing all implementing classes to support JPA
  2. Specifying the JPA support in a different interface, not a subclass from Repository. Then all classes could choose whether to implement JPA independent of their specific Repository interface. See Serializable for an example. This is the de facto solution for signalling that a class supports a specific feature like "serialization", or maybe "persistence" like in this case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM