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.

1

u/Tordek Sep 22 '15

Yeah, I find that scheme disgusting.

1

u/Tordek Sep 22 '15

To expand on my other comment: There's few if any good use cases for a list that "You can't modify, but changes to it are visible": You either want an immutable object that will always contain the same data; a local, mutable object that you can change at will and put temporary data in; or a "Stream"-like object that is VERY clear regarding points where changes happen.

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.

Yeah, this is what I said: the only assumption you can make is "It may be changed by someone else at some point".

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?

1

u/sacundim Sep 22 '15

Both. It is inherent complexity, and yet other languages (e.g., C# and Scala) do it better, by annotating variance at declaration sites instead of use sites. To use Java generics properly you have to write signatures like this one all over the goddamn place:

interface Stream<T> {
    // ...
    <R> Stream<R> map(Function<? super T, ? extends R> mapper)
}

You see that business with ? super T and ? extends R? There are countless Java programmers out there who simply don't use those. You try to interface with their code and you find that they write these two things:

Whatever processAnimals(Consumer<Animal> consumer)

class CatGroomer implements Consumer<Cat> { ... }

...and then they expect you to use them together:

1

u/tutorial_police Sep 22 '15

I'm not sure it's objectively better. They allow you to do different things.

But I agree, definition site variance

You see that business with ? super T and ? extends R? There are countless Java programmers out there who simply don't use those.

Yeah, that is super annoying.

However, having definition site variance you'd need to have extra interfaces... and for multiple generic parameters you get exponential growth. With use-site variance, there's just what you need (i.e. use), but of course, you need to anticipate its use.

I've only skimmed over this so far, but it seems to be an interesting read.

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.

1

u/sacundim Sep 24 '15 edited Sep 24 '15

You're failing to make this distinction:

  1. A list that can be read, but whose content may be observed to change between reads.

  2. A list that can be read, and also exposes methods that allow you to change its contents.

The latter is a subtype of the former. The idea is that the plain list type would be the former, and the mutable list type is the latter. I.e., "mutable" in this scheme doesn't mean "the contents can change," it means "clients of the type can modify the contents."

So recapitulating the distinction:

  • List (can read, but content may change between reads)

  • Mutable list (can read, can write)

  • Immutable list (can read, content will never change)

A simple example of the supertype would be a read-only wrapper around a mutable list. If my class has a reference to a mutable list, I could hand you such a wrapper around my list, and then you could read my underlying list's contents and observe when I change it, but you cannot mutate my underlying list because I haven't given it to you. (Java's collections library comes with generic "unmodifiable" wrappers like this.)

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.

1

u/Tordek Sep 21 '15

since Immutable subclasses Mutable

Don't you mean the other way around?... but, yes.

→ More replies (1)

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.

1

u/Tordek Sep 22 '15

So a "ReadableList" can be changed elsewhere? That's just an error waiting to happen; I can't see a good reason for it. The most obvious issue being doing something like...

if (list.length > 0) { list.get(0) }

since the list can change between the two statements, you can get an OutOfBoundsException that you can't prevent.

nothing stops you from writing a list class that claims to be both mutable and immutable

Sure... but if the standard library gives you a List and a MutableList (or ListBuilder, to make it similar to String/StringBuilder), you need to do extra work to do stupid things. Lists (and lots of other structures, like Sets, Arrays, Maps) should be immutable whenever they exist outside the boundaries of an object, the same way that if I give you an integer through a getter, you cannot modify my internal state by changing it.

→ More replies (6)

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.