Guava's ImmutableCollection
has sub-classes like ImmutableList
that are (non-extendable) abstract classes rather than interfaces. The documentation says this is to prevent external subtyping. On the other hand, the documentation also says they
should be thought of as interfaces in every important sense
But isn't the ability to externally subtype an important sense of an interface? For instance, if ImmutableList
was an interface, I could have a method signature like
public ImmutableList<String> getNames();
(as is the Guava recommendation), and then have the flexibility to swap in a custom implementation of ImmutableList
in the future. However, since in reality it is an abstract class, I don't have this flexibility, and therefore am bound to Guava's implementations. Thus, if I want to maintain this flexibility, I'd have to revert to using the more general return type of List
, which no longer conveys the helpful information about immutability to callers:
public List<String> getNames();
So why is it important that these not be externally sub-typed? One answer might be that the Guava designers don't trust external implementors to properly support the required semantics, but List
itself actually has pretty extensive contract, and no one is preventing custom implementations of that. Or are there other reasons?
It's because there's no way to have the type ImmutableList
guarantee immutability if it's an interface.
And no, I don't think the ability for anyone to write their own implementation of an interface
is a necessary property of all interfaces. Consider, for example, sealed types, which only allow a specific set of implementations that are defined in the same file. They can still be interface
s (there's a proposal that includes sealed interface
for Java here) without allowing anyone in the world to create an implementation of them.
I'd also be really curious as to why you'd think you might want your own custom implementation of something super-simple like an immutable list.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With