The appropriate way to subclass Guava ImmutableSet

I have a line by line class

class Receipt { private Set<Order> orders; public Receipt(Set<Order> orders) { this.orders = ImmutableSet.copyOf(orders) } } 

It served me well.

However, due to some erasure and persistence issues that I encounter, I would like to introduce a form

 class OrderSet extends Set<Order> {} 

Obviously, I cannot extend Set<Order> , since this is an interface. I would like my implementation to be immutable. However, I cannot extend the ImmutableSet<Order> because the state of the documents:

Note. Although this class is not final, it cannot be a subclass outside its package, since it does not have public or protected constructors. Thus, instances of this type guarantee immutability.

I could use composition by providing the OrderSet collection of ImmutableSet support and delegating all the Set methods to it. However, this seems redundant.

Is there any other way to get a non-general subclass here?

+6
source share
1 answer

No, the composition is not too much, this is exactly what you need.

You should create your OrderSet as follows, because, as Louis emphasizes in the comments, this use case is exactly what they are intended for:

 public class OrderSet extends ForwardingSet<Order> { private final ImmutableSet<Order> orders; public class OrderSet (Set<Order> orders) { this.orders = ImmutableSet.copyOf(orders); } protected ImmutableSet<Order> delegate() { return orders; } } 

Immutable classes in Guava are designed so that you don't extend them. You have to use composition, and that is exactly the right way.

+13
source

Source: https://habr.com/ru/post/907481/


All Articles