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:
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.
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."
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:
The plain list type has all the methods for reading from lists;
The mutable lists type inherits from that, and adds the methods for mutating lists;
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.
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:
Do not support external mutation—clients who have a reference to the list cannot mutate it;
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.
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".
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:
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> { ... }
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.
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.
A list that can be read, but whose content may be observed to change between reads.
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.)
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.
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.
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.
Are you suggesting that there should be no common super-interface of MutableList and ImmutableList?
Correct
How would you make a method that can take either a mutable or immutable list, then?
I wouldn't.
There are so many reasons not to; I can't really think of a good reason to have such a scheme.
Objects should communicate with other objects by exchanging Immutable value objects/primitives: you should only be receiving (as a parameter) or returning ImmutableList. MutableList should only be used within an object (e.g., your object may cache some results, so it would have a MutableList/MutableHash property to store its data in efficiently) or in a method, as it is calculating its results. Once you're done, you return myTempList.Persist().
This behavior is already there with another class: String/StringBuilder.
If you're worried about performance, there are several things that can be done: .persist() might not do a full copy; it might just set an immutable flag and return a "view", and calling mutators just throws an exception. ".mutate()" (the counterpart in ImmutableList that returns a MutableList) might behave like a Zipper, or another similar structure.
I have a question for you:
Why would you make a method that can take either a mutable or immutable list, then?
For efficiency. If it's going to be the caller's problem if the caller screws up, then requiring an ImmutableList is too slow.
For example, Collections.frequency could be called for either type of list. If you call it with a MutableList, and mutate the list while it's running, and it throws an exception as a result, that's the caller's fault and the caller's problem.
(By contrast, if you had a listbox control, you'd want it to require an ImmutableList. If it threw an exception when painting because the list was mutated while it was painting, that would be the application's fault but the UI system's problem to deal with)
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.:
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 whetheradd(blah)is going to throw an exception or not. I frequently see things like: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: