111 points · by javinpaul · 11y ago · 113 comments
It is also horrifying.
C programmers do that with pre-processor. C++ programmers do that with templates and pre-processor. Java programmers do that with annotations.
It is also horrifying.
[1]: Switching to another language on the same platform (JVM/JS) lowers the cost considerably, but it is still high.
Personally, I've been using Java for over a decade, and a few years ago I added Clojure to the mix and expect it to serve me for over a decade, as well. I like them both and believe they both qualify as good picks. I'm also adding Kotlin now, too, mostly because its switching cost and added risk are practically zero.
[1]: for reasons other than targeting a new platform
But, I'm sure someday we'll all discover your one true God... Err... Programming language, like the lispers and smalltalkers, the rubyists and the haskellers, the C++ fanatics and the C faithful...
Don't fall for that trap. What matters is that you build solid software that delivers value.
If you mean immutability, it's doesn't make sense to single out Java, since immutability was not significantly valued by any mainstream language until the 2000s (of course Haskell and various MLs existed before, but I'm talking about popular mindshare).
It was only until concurrency/parallelization/multi-core became more important that immutability-by-default gained much traction.
Nowadays, Java feels like the victim of the OO hype: mutable by default, static methods being the only escape hatch from OO, only predefined value types (yes, I know, Java 9). People always say that Go is like pre-generics Java, but it at least doesn't make two of the aforementioned mistakes.
This only works for invariants that constrain the state of a single object. Realistically, invariants that constrain the state of multiple objects are a necessity, and no amount of in-object validation will help you enforce those.
This framework just makes it a little bit shorter to type as it automatically generates some boilerplate code.
But, from an OOP perspective, modelling state changes is natural and desirable. So mutability seems a sensible default.
It's only the recognition of issues that can arise from state changes that has us wanting to lop off the entire feature. A rather strange and drastic "solution" in my view.
However, totally unconstrained mutability is definitely a shortcoming. The ability to look at a type signature and be immediately able to tell what might or might not change is a big win for maintainability, especially in big projects.
By the way, constraining mutability doesn't require a purely functional language. The ML family (Standard ML, OCaml) allows all expressions to have arbitrary side effects (when evaluated), but all values other than reference cells are immutable.
The one thing that tripped me up when I tried to use it is that you can't add other library annotations. For example, I couldn't change the json serialized field name using Gson's @SerializedName("custom_naming").
[1] http://immutables.github.io/immutable.html#serialization
I know that Lombok had to change their code quite frequently to fit with different javac versions for a while, which means that this project becoming stale could be a problem.
What am I missing?
There are many others, including tainting types, linear types, physical unit types and more.
[1]: http://types.cs.washington.edu/checker-framework/current/che...
A programming library with copy that looks like it's written by a marketeer – well, why not, I guess :-)
I'm all for tools that make immutability easier; the lack of immutable objects is one of my main sources of cognitive dissonance when programming in Go instead of Java.
[1] http://immutables.github.io/CompareImmutables.pdf
EDIT
To be clear, it seems like a nice boiler-plate avoidance technique (which Java could always use more of). But you're implying that there's some other significant underlying problem this solves and I don't see it.
In order for a class to be immutable, all its fields need to be be immutable and final. Immutability got to be recursive.
Also, in Java, the class should be final, otherwise nothing prevents anyone from extending it and pass a mutable data structure instead of the immutable one you'd expect
Edit : added the "in java", as we could imagine another language where immutable doesn't require objects to be final.
If I have:
private final Map<String, String> map = new HashMap<>();
I cannot say map = someOtherMap;, but I can still say map.put("key", "value");.
Plus, you can't statically know if the collection you're passed is immutable or not. Trying to modify it will just blow up at runtime.
They're not really comparable.
This is code generation for builders, getters, etc. The idea is that you write less of the boilerplate that you'd write if you were rolling your own immutable POJOs.
Plus, unless I'm mis-reading the docs, it also handles certain collection types transparently. (Which obviously just throwing final on a property won't do.)
There are other benefits to immutability, to be sure, but I appear to be the rare voice that finds the dictum to "make everything immutable" to be overstated. And, we seem to ignore the code bloat that comes along with it--builders and the like, as well as performance implications.
Of course we solve the challenges that mutability can introduce by lopping it off altogether, but at what cost? It's really not too far from solving problems that object misuse can introduce by getting rid of objects.
Replace all setters with builders, annotations, etc. Do not ever change an object's state. Ever! Run this Mutability Detector on your code to ensure you are not allowing something to be mutable. At all costs, kill those language features that allow object state to be changed!
At what point have we jumped the shark?
Maybe others believe in moderation as do I, and I just happen to be reading more of the forceful champions of immutability lately. But, they seem pretty loud and I have learned that edicts to never or always do something warrant great suspicion.
> Of course we solve the challenges that mutability can introduce by lopping it off altogether, but at what cost? It's really not too far from solving problems that object misuse can introduce by getting rid of objects.
At what cost then? I can point to specific scenarios where objects are useful and languages without them (e.g. Haskell) solve the problem less elegantly. Can you say the same for mutability? Have you got a specific business problem that you've solved with and without mutability and found that the mutability made it better?
(FWIW my position is: no unmanaged mutability beyond method scope. Local mutability is fine, but anything that crosses method boundaries should be explicitly managed using e.g. State)
>At what cost then?
If a language offers a construct for achieving a certain goal, and you opt to bypass that construct to create a parallel construct, then you are necessarily creating additional cost. But, it's actually worse than that because it goes beyond creation of parallel constructs: it also includes working to actively suppress the built-in language constructs.
And now we are creating immutability tools and new annotations, and running Mutability Detection, etc. as if mutability itself is a defect and stamping it out automatically improves code quality.
>Have you got a specific business problem that you've solved with and without mutability
Yes. Every bit of code I've written before the age of Mutability-is-Pure-Evil. That code worked well without the additional code bloat, object copying, and performance penalties associated with defeating natural language constructs. No annotations. No builders everywhere. Just pure, clean, intuitive code whereby other developers were required to actually understand the design before using it.
You need to set a property? Then, set it. Don't construct a completely new object with a builder, just to update the zip code. In a multithreaded environment? Sorry, you need to understand concurrency issues. No amount of dumbing down objects is going to make up for your lack of understanding there.
Otherwise, let's stop calling immutability OOP. What people really want is to pass around a struct and have procedural code wrapped in other objects perform operations on it.
And, sorry. Moderation is key. Your use of "internal mutability" is actually a nod to moderation. When people find themselves repeating that something is always evil, it should trip a mental alarm. Sure, there are cases wherein immutability might be a reasonable way to solve a problem, but definitively stating that it is always the right approach is shark-jumping.
No, it's not. I'm talking about within a single method, which inherently means belonging to a single thread.
> But, it's actually worse than that because it goes beyond creation of parallel constructs: it also includes working to actively suppress the built-in language constructs.
Again, some language constructs are just bad. E.g. I believe Gosling has said he wishes he never put checked exceptions in Java.
> You need to set a property? Then, set it. Don't construct a completely new object with a builder, just to update the zip code. In a multithreaded environment? Sorry, you need to understand concurrency issues. No amount of dumbing down objects is going to make up for your lack of understanding there.
On the contrary, more restrictive models really are easier to understand.
Yes, I more than once had to fix code in an natural language processing library, because multi-threaded Jersey services led to either crashes or partial annotations literally ending up in the wrong request. In the cases where I had access to the code, I rewrote the classes to be immutable (all state is created and passed between method calls), which fixed it.
In one natural language parser that we couldn't patch, I had to create one full parser instance per thread (weighing in at ~1-2GB), because the class was mutable and did not use correct locking. (So, we ended up creating a couple of parsers at startup and putting them in an object pool.)
Again, that's not to say that immutability never has a place.
Of course, mutable state cannot be abolished everywhere (often for efficiency reasons). In such cases, you should indeed understand the concurrency primitives.
That said, sometimes state simply has to change, and anything else is just ideology.
But if I were to start a project, I would start with immutability by default and go from there, chiefly because when you find yourself needing to add additional threads and share data, I consider the transition from mutable to immutable would be more difficult than the inverse.
Another perspective: mutability is a feature that can be used in certain contexts (and QUITE useful there) but nothing intrinsic to the feature (in Java, at least) enforces the contexts' prerequisites (i.e. thread-safe access), and thus it is easy to end up with runtime errors when the environment of your project shifts.
Immutability, OTOH, makes fewer contextual assumptions (or perhaps more tractable ones).
Said perhaps more pithily: when mutable-by-default, your resultant architecture will frequently hinge on mutability. If you instead start with immutability, the immutability will be less of a crutch than the mutability would have been.
I guess that's where I differ: To my mind the mutability construct is not supposed to provide this. Instead, enforcing thread-safety should involve the use of concurrency constructs.
And, that's the thing: OOP represents a stateful paradigm, in the sense that operations may be performed which mutate the state of an object. When we bring out the Hammer of Immutability to prevent potential concurrency issues, we are basically saying that we no longer want to be OO because of an unrelated requirement. Let's turn the objects into structs that can only be passed around and copied so we don't accidentally screw something up. This, rather than using the language's actual concurrency constructs to safely share data.
>it is easy to end up with runtime errors when the environment of your project shifts
I can't remember when this has happened to me and I'm genuinely having trouble seeing the case. If I have an object which suddenly must be shared across another thread, then I generally cease to access it on the initial thread without some sort of synchronization.
So, I just don't see how you'd suddenly share data across threads under any model without very careful consideration of what's being shared and why. What operations will be performed with the data as input, what will be the output, and how/when do we communicate this to other threads?
Once you've done that analysis, then you have a blueprint for how to safely share data the right way.
val immutableList = List(1, 2, 3)
val immutableMap = Map("foo" -> "bar")
var mutableString = "foo"
val mutableList = collection.mutable.List(1, 2, 3)
val mutableMap = collection.mutable.Map("foo" -> "bar")
A similar example in Scala would be a class that has only 'val' types and no 'var' types, but read through the stackoverflow post to see the complexities.
WAT
* DRY for cross-cutting concerns, like database transactions, logging, dependency injection, serialization, validation, web controllers/endpoints... basically, macros for Java.
* Less code means less chance for error - even if that code was generated at some point in the past, it will need to change in the future, and the future developer may do the change manually and might introduce mistakes. Using annotations can help enforce patterns.
Looks like immutables transform the code in even more spaghettis.
Just looking at the "get started", it looks like the author voluntarily ignores all the java conventions around variables and getters/setters.
I might be wrong on this, but I suspect this framework heavily relies on introspection, which in my experience has always led to very hard to debug and explore code.
Functionality overlap is not particularly clear with Checker framework, in fact Immutable users often use Checker framework also. There are other tools like AutoValue, FreeBuilder, Lombok where I can see more similarities, but with important differences.
>> Looks like immutables transform the code in even more spaghettis.
I would not agree, but you should look at real world codebases like [1] or [2] which use immutables.
>> Just looking at the "get started", it looks like the author voluntarily ignores all the java conventions around variables and getters/setters.
Immutables support getters convention and you can configure any other convention you have, see [3].
>> I might be wrong on this, but I suspect this framework heavily relies on introspection, which in my experience has always led to very hard to debug and explore code.
Immutables uses standard APIs of annotation processing. You can take a look at example generated code [4].
[1] https://github.com/facebook/buck
[2] https://github.com/glowroot/glowroot