Inheritance, composition and default methods

前端 未结 5 627
日久生厌
日久生厌 2021-02-08 05:28

It is usually admitted that extending implementations of an interface through inheritance is not best practice, and that composition (eg. implementing the interface again from s

5条回答
  •  时光说笑
    2021-02-08 05:53

    I don't really understand the big issue here. You can still back your UserDatabase with an ArrayList even if not extending it, and get the performance by delegation. You do not need to extend it to get the performance.

    public class UserDatabase implements List{
       private ArrayList list = new ArrayList();
    
       // implementation ...
    
       // delegate
       public Spliterator() spliterator() { return list.spliterator(); }
    }
    

    Your two points are not changing this. If you know "ArrayList has its own, more efficient implementation of spliterator()", then you can delegate it to your backing instance, and if you do not know, then the default method takes care of it.

    I am still unsure whether it really makes any sense to implement the List interface, unless you are explicitly making a reusable Collection library. Better create your own API for such one-offs that does not come with future problems through the inheritance (or interface) chain.

提交回复
热议问题