I try to program by interface. It gives the code more flexibility. More details.
I have an issue however with the Java collections classes, which are always used. Checkstyle by default sets all implementing classes of the collections as illegal types. However, I don’t agree with it.
For instance: Set.remove(Object) makes no promises, it says it could simply throw a UnsupportedOperationException if the method isn’t supported. This isn’t usually a problem as most of the time the implementation is HashSet or possibly LinkedHashSet. Sometimes, however, I use ImmutableSet, which throws a UOE on remove. What I would like to do is return something which is a Set but which can be modified with remove.
Scala collections I think have a much nicer API.
For instance, Scala’s Set defines that the – method “Creates a new set with a given element removed from this set”, which is also the functionality of the mutable version (scala.collection.mutable.Set). The mutable version, however, also adds a -= method to modify the set in-place, something that only makes sense for mutable collections. But mutable.Set doesn’t define the implementation used, so it can be used as the type of any parameter or field that you declare to be a Set (no duplicate elements) and modifiable (-=, +=, etc).
If only, if only. If only Java’s collections had interfaces for mutable collections without implementation, that way I could return a MutableSet, leaving the user able to remove object (without having to create a new Set with the contents of the original Set), without having to specify the implementation..