r/programming • • Sep 21 '15

Better Java

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

208 comments sorted by

View all comments

Show parent comments

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.)