Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutability and General vs. Specific Types

This is in the context of creating an interface/API.

Best practices suggest using general rather than specific types in interfaces - e.g. Map rather than HashMap.

Best practices also suggest preferring immutable types over mutable ones.

So considering both of these suggestions (and leaving aside concerns about performance/memory-footprint, 3rd-party-libraries/dependencies and convenience/functionality) should a method in a public interface look like this

public List<SomeClass> someMethod(...)

or rather this

public ImmutableList<SomeClass> someMethod(...)
like image 665
Dexter Avatar asked Mar 21 '23 10:03

Dexter


1 Answers

When this has been discussed among the Guava folks, the following has been said:

The basic advice for types exchanged by APIs is this: choose the most general type that still conveys the relevant semantic information.

I consider the trio of semantic guarantees made by ImmutableCollection to be extremely relevant for return values in almost any circumstance (those three being immutability, lack of null elements and guaranteed iteration order). So I would virtually always return ImmutableSet, not Set.

We would really like people to view ImmutableSet etc. as being interfaces in every important sense of the word. There are only two reasons they are not: reliability of the immutability guarantee, and the fact that Java won't allow static methods on interfaces until JDK 8, and we wanted them there for convenience.

Most people think ImmutableList is an implementation for this reason, but there are actually several to dozens of different implementations of some of these types; you just don't see them.

like image 159
Louis Wasserman Avatar answered Apr 02 '23 05:04

Louis Wasserman