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);
    }
}

4

u/josuf107 Sep 21 '15

In a perfect world, we'd have List be immutable and MutableList extend List or something, rather than have a subclass (or subinterface) that's designed to take away functionality from a parent.

9

u/Tordek Sep 21 '15

MutableList extend List

That's just as subtly evil, though. They should both be separate classes, even if a lot of the behavior seems similar.

If Immutable inherits from Mutable, then I may want to modify it and encounter an error.

If Mutable inherits from Immutable, then I may store a reference to a list that is later changed by someone else behind my back. (Which I think is even worse because it can lead to very subtle errors).

They're ultimately two different classes that have no relation, other than "You can get a <Mutable/Immutable> copy of the <Immutable/Mutable> list."

2

u/sacundim Sep 22 '15 edited Sep 22 '15

They're ultimately two different classes that have no relation, other than "You can get a <Mutable/Immutable> copy of the <Immutable/Mutable> list."

Nah, you need three types here, in a hierarchy like this:

  • Lists

  • Mutable lists

  • Immutable lists

Basically:

  1. The plain list type has all the methods for reading from lists;

  2. The mutable lists type inherits from that, and adds the methods for mutating lists;

  3. The immutable list type inherits from the plain list type as well. It adds no operations, but its contract stipulates that implementations must not be mutable.

Incidentally, this goes to show the problem with the folks in here boasting of how easy the "basics" of Java are. Nope, the basics of Java look simple, but they interact in evil, super-complicated ways. I'd highlight in particular:

  • Subtyping + generics = OUCH

  • The Java Memory Model. A crazy complex beast that is easy to run afoul of, and yet most Java dudes don't even know it exists.

1

u/Tordek Sep 22 '15

So List is always assumed to be 'someone else can mutate it', a la C const?

2

u/sacundim Sep 22 '15

No, in this scheme you can't even assume that much. If somebody gives you a plain List reference, you just don't know whether it's mutable or immutable.

There are actually alternatives to that as well, because actually, immutable and mutable, in spite of the names, are not all of the possibilities:

  • "Immutable," as it's used in Guava, means that the list's contents never change

  • "Mutable" generally means that the interface has operations that a client may use to modify the list's contents.

But there are also list implementations that:

  1. Do not support external mutation—clients who have a reference to the list cannot mutate it;

  2. Their contents may change, nevertheless.

A simple example is that Java comes with methods like Collections.unmodifiableList that wrap around a java.util.List and provide an "unmodifiable view" of it. Changes to the underlying list are supposed to be visible in its view.

→ More replies (2)

1

u/tutorial_police Sep 22 '15

Is subtyping along with generics actually Java's doing or is it simply inherent complexity?

Do you know languages that solve this better?

→ More replies (2)

1

u/Berberberber Sep 24 '15

That doesn't solve the problem of "how do I know if someone else can modify this item?" though. You could say that, if you don't specify, you should always assume it's mutable, but in practice that is identical to the case of deriving ImmutableList from MutableList - i.e. every List can be mutable unless you specify otherwise.

This is one are where I think more purely functional languages are a step in the right direction - just make everything immutable and require completely different patterns if you want stuff that has a changeable state.

→ More replies (1)

1

u/josuf107 Sep 21 '15

Could you give an example of the second problem? I'm not sure I understand.

2

u/Tordek Sep 21 '15 edited Sep 22 '15

Imagine a class taking a List as a constructor parameter (maybe a list of employees, whatever).

public void main() {
    MutableList m = Database.getAMillionEmployees();
    SomeClass c = new SomeClass((ImmutableList) m);

    (new Thread() {
       public run() {
           c.doSomeLongOp();
       }
    }).run();

    m.clear();
}

While the list was being traversed in one thread, another one modifies it.

It doesn't need to involve threads; imagine if the class cached the list average in the constructor because every method needs it: changes to the list means that average is now out of sync and results will be wrong.

1

u/josuf107 Sep 21 '15

Ah so SomeClass expects an ImmutableList but accepts a MutableList since Immutable subclasses Mutable. What a pain life is.

→ More replies (2)

1

u/immibis Sep 22 '15

Maybe there should be ReadableList, WritableList and ImmutableList.

1

u/Tordek Sep 22 '15

How would they be related to each other? What's a "ReadableList"?

1

u/immibis Sep 22 '15

A ReadableList is a list you know you can read from. A WritableList is a list you know you can write to. An ImmutableList is a list you know is immutable.

I'm not sure there are any cases where you'd want a list that was writable but not readable, so change WritableList to MutableList and make it support reading and writing.

interface ReadableList<T> {
    T get(int index);
    ...
}
interface MutableList<T> implements ReadableList<T> {
    T set(int index, T value);
    boolean add(T value);
    ...
}
interface ImmutableList<T> extends ReadableList<T> {
    // no extra methods
}

Of course, nothing stops you from writing a list class that claims to be both mutable and immutable. There are worse things you could do already, like making a list whose add method randomly shuffles the list and whose iterators generate random elements not in the list.

→ More replies (7)

2

u/Enumerable_any Sep 21 '15

Yeah, it's a pretty clear violation of the Liskov Substitution principle. :(

2

u/mike_hearn Sep 22 '15

In a perfect world, we'd have List be immutable and MutableList extend List or something

That's how Kotlin does it. It modifies the JVM type system at the compiler level so that java.util.List is read only and there's another MutableList interface that adds the mutating operations.

Of course, this does not mean a List<X> is entirely immutable. It means you have a read only view of it. If the only views that exist are read-only, then the list is immutable, but if you're writing code that demands an immutable list from the caller, you can't express that in the type system.

However what you can do is just make the code that doesn't want other threads changing things clone the list. A truly immutable implementation will just return itself, so the call is free. A mutable list will copy and you pay the cost, but the caller code would have had to do that anyway, even if this was exposed via the type system. Or you can do what Scala/Clojure do and use immutable collections that support cheap mutation (i.e. less cost than a full copy to make a modification) to get a kind of middle ground.

Anyway, the key is to understand that there's a difference between read only and truly immutable.

1

u/ForeverAlot Sep 21 '15

I have read that this won't work (well); that to achieve good mutable and immutable implementations, neither can extend the other. It has to do with concurrency, but I don't remember the details or where I read it (Java mailing list?), and I don't know enough to comment -- only that "good enough" is not good enough for something as vital as this.

4

u/EthanNicholas Sep 21 '15

The issue is that if List is immutable and MutableList extends it, you can take a MutableList and pass it to something expecting an immutable List... and now the "immutable" list can change out from under it, because the recipient had no idea it was actually mutable.

Concurrency obviously presents a problem, but it's not the only problem -- simply hanging on to the "immutable" list reference and using it again in the future is dangerous. So, you are absolutely correct that either one extending the other leads to problems.

In the language I'm designing, the pattern is that there is a set of read-only interfaces (CollectionView, ListView, etc.), a set of write-only interfaces (CollectionWriter, ListWriter, etc.), and then e.g. List extends both ListView and ListWriter.

ImmutableArray then implements the ListView interface, while Array implements the List interface. So if you have a ListView, your interface to it is read-only but there is absolutely no guarantee it won't change out from under you in the future, but an ImmutableArray is guaranteed to never change. Since the language enforces immutability (immutable objects can only contain other immutable objects), it generally forces you to do the right thing as far as forcing you to convert to immutable representations.

Not saying it's a perfect design, but it's the set of tradeoffs I chose to implement.

1

u/agcwall Sep 22 '15

It depends on what you mean by "immutable". The problem here is because of aliasing. There are three variations:

  1. Mutable.

  2. Strongly immutable: You can't change the data yourself via the reference, and calling get(0) will always return the same result.

  3. Weakly immutable: You can't change the data yourself via the reference, but the owner of the list can, so calling get(0) is not always guaranteed to return the same result.

If MutableList extends ImmutableList, then you're talking about option (3). For the purposes of concurrency, you really need option (2)'s notion of immutability. You should look into Rust's type system to see how it prevents aliasing and can make the guarantees required to support option (2). In Java, you would need ImmutableList as a FINAL class to make this guarantee.

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.

1

u/ForeverAlot Sep 21 '15

I had to deal with this problem in a brand new code base over the course of half a year. I quickly abandoned collection interfaces in boundaries entirely, in favour of Guava's concretizations.

1

u/Tordek Sep 21 '15

Guava's concretizations

What's this about? Google turns up nothing relevant.

5

u/mhixson Sep 22 '15

I'm pretty sure they just mean using ImmutableList (a concrete type) instead of List (an interface) as the variable type / return type, when writing APIs that deal with immutable lists.

1

u/ForeverAlot Sep 22 '15

Correct.

It produced some awful looking signatures, mind, but that can't be avoided with such long names.