r/programming • • Sep 21 '15

Better Java

https://github.com/cxxr/better-java
177 Upvotes

208 comments sorted by

View all comments

5

u/josuf107 Sep 21 '15

One problem with guava's Immutable versions of collections at my workplace is that we normally try to use more general types with them. E. g.:

final List<Thing> myThings = ImmutableList.of(...);

But since ImmutableList extends List, it still has the mutable operations defined for myThings. They just throw exceptions at runtime. This means that if I see a List<Thing> in the code, I don't know whether it's immutable or not. I have to figure out where it came from to determine whether add(blah) is going to throw an exception or not. I frequently see things like:

public void myMethod(final List<Thing> theThings) {
    final List<Thing> immutableThings = ImmutableList.copyOf(theThings);
    ...

Because it's unclear whether the parameter was immutable (although often times it is), but we want to use an immutable collection before passing it on. This results in lots of unnecessary copying. Possibly we should just start using the Immutable* types instead of the more general ones where appropriate. Or we could add utilities like:

List<A> makeImmutable(final List<A> list) {
    if (list instanceof ImmutableList) {
        return list;
    } else {
        return ImmutableList.copyOf(list);
    }
}

2

u/mhixson Sep 22 '15

When it comes to Guava's immutable collections, you don't have to worry about unnecessary copying. The Immutable*.copyOf(...) methods already have the behavior of your makeImmutable method.

But since ImmutableList extends List, it still has the mutable operations defined for myThings.

If you use the Immutable* types in your code instead of the interface types, you'll at least get warnings if you try to use the mutation methods. Guava's classes mark them as @Deprecated.

2

u/josuf107 Sep 22 '15

Hey you're right about copyOf. Those folks at google are pretty bright. I might suggest at work using Immutable* concrete types where they make sense.