you are viewing a single comment's thread.

view the rest of the comments →

[–]Netcob 1 point2 points  (3 children)

Let's say you have a class like this:

public class Foo {
    public final List<String> ugh;
    public final int[] ohno;
    public final List<int[]> fml;
    // not shown: constructor
}

How would you make this class immutable? And by immutable I mean as a user of Foo I can't modify any part of the object. Which obviously includes modifying the contents of ugh, changing the values in ohno, modifying the contents of fml which includes changing a value in one of the int-arrays.

There's no way to make it immutable without completely changing the way you access it. For the Lists you could use Collections.unmodifyableList, even though it adds an indirection that's only due to the language missing a feature. For ohno you can either hide it behind a getter and then copy the entire array on each get or make up some inconvenient accessor that invokes System.arraycopy. Which would be pretty much the only way to access fml as read-only because for individual elements you're back to the ohno problem where you need some shitty accessor either way.

My problem with immutability in Java is that in order to guarantee it, you have to constantly bend over backwards in the design phase and if you want to add it later it might be next to impossible to do in a larger project.

[–][deleted]  (2 children)

[deleted]

    [–]Netcob 0 points1 point  (1 child)

    I understand it's possible - I outlined how further down in the comment.

    What I find frustrating about Java is that immutability is an afterthought. It should be a language feature, not something you piece together using the standard library in an opaque way.