Immutable annotations for Java
immutables.github.io
immutables.github.io
It is also horrifying.
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
[1]: http://www.ozy.com/rising-stars/taavi-kotka-is-putting-the-e...
I agree with you about languages and targeting 10+ years with it. Stability is worth more than anything to me, out of the box performance also important (this tend to be great for older languages) not to mention the std library quality. For these reasons Java is an excellent choice.
Clojure came to me as a total surprise, since I haven't studied CS and because I was surrounded with Perl/Java engineers for a long time I haven't heard about Lisp till 2011. It changed my approach to software engineering a lot. It is absolutely eye opening, mind blowing and all that jazz.
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...
None of this has anything to do with objective technical superiority of one solution or another, assuming you could make that case definitively. And if one could make that case, technical superiority is only one input into a much more complicated decision-making process.
Again: there is no one true language. There never was and there never will be. Our entire industry, hell, all industries, operate based on tradeoffs, whether those be business, technical, political, or other. Why would programming language selection be any different?
Don't fall for that trap. What matters is that you build solid software that delivers value.
C programmers do that with pre-processor. C++ programmers do that with templates and pre-processor. Java programmers do that with annotations.
I see you as a hero and hope for a 1/1000 of your productivity when I peak.
Glad to see you were a Schemer too.
That Lisp is written for the virtual machine originally written for Java.
It is 2015, please let us stop the FUD at least now :)
PS: I love Java and use it for my day job. Just a few days back I was reading about AutoValue and Immutabiltiy and wishing that Java had more power that would make these hacks unnecessary. I am not saying Lisp is the greatest, but Java definitely feels like assembly when you reach the edges and one has to wait for years to get updates.
I don't like Java. I don't like Java at all. (I prefer Clojure or Scala, depending.) But I recognize why it is where it is, and Paul Graham saying Paul Graham things doesn't really change reality.
This framework just makes it a little bit shorter to type as it automatically generates some boilerplate code.
Of course, you cannot get the same guarantees that e.g. Haskell provides. Moreover, unless you return concrete types, that Map<> being returned by a method could be mutable or immutable (it's your guess ;), or hopefully in the documentation).
(And no, Collections.immutableMap doesn't.)
(And then there are problems with the JVM bytecode as well - do you know you can pass 2 into a function expecting a boolean? And sometimes it'll get treated as true and sometimes as false? The JVM is "wonderful" like that.)
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.
As cognitive resources become the bottleneck, it's sensible to invest in tools that decrease cognitive burden. So we're seeing an upswing in popularity with methods and techniques aimed at limiting the amount of unnecessary, incidental complexity generated. "Easier to use" is nice, but "less complex" is imperative right now.
Immutability is one of those techniques that can be leveraged to limit growth of complexity.
What you're saying is perfectly rational, right down to your emphasis on can. I don't take exception to immutability as one tool. My problem is with the notion that it is the only tool and the corollary that mutability is always wrong.
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.
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.
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
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.)
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.
Also, unmodifiableCollection doesn't make the collection you pass in immutable; it creates a new object through which you can access it as long as you don't modify it. Anybody holding a reference to the original object can still change the object.
I think you can even somewhat break the collection by changing objects inside it if doing that changes their hashcode (for sets and dictionaries, such a change may have to reinsert the item in the collection to make sure that you can still retrieve it)
If you weren't using this library, you could achieve something similar with, e.g.,
someImmutableSet = Collections.unmodifiableSet(new HashSet<E>(someSet));
I think this library really is about making immutable objects accessible, i.e., taking away the boiler plate. Hand-writing immutable (and potentially mutable) implementations on top of interfaces for a whole set of DTOs is super annoying.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.
It wouldnt work. If MutableList<E> extends ImmutableList<E> then every MutableList is also an ImmutableList. This way you can be forced to return a MutableList, but not an ImmutableList.
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.
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.
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.
That said, sometimes state simply has to change, and anything else is just ideology.
Of course, mutable state cannot be abolished everywhere (often for efficiency reasons). In such cases, you should indeed understand the concurrency primitives.
> 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.
If your method is modifying data non-atomically, then you can still have issues with data consistency when another thread attempts to access the object in the middle of your update. You're going to need to synchronize access in some manner.
>Some language constructs are just bad...checked exceptions...
Checked exceptions are not an integral part of OO design. Objects, along with the concept of properties (i.e. state) are.
>more restrictive models really are easier to understand
That's simply not a universal truth.
Externally-visible data should not be mutable.
> That's simply not a universal truth.
Let's talk specifics then. My preferred model is: every piece of persistent (beyond a single method scope) mutable state is owned by an actor, and accesses to that state are performed by sending State values to that actor and receiving values back. The type system enforces that any state modification happens in the appropriate actor; since State is an ordinary value you can refactor safely without worrying that you're changing concurrency boundaries. Monadic syntax (for/yield) makes it easy to compose state changes that should happen atomically, and since the call to actually perform the modification is explicit, it's easy to see which changes are atomic and which are not.
This doesn't automatically solve the problem. If two threads invoke methods which mutate (or read) the internal state, then inconsistencies can result if not properly synchronized.
>Let's talk specifics
You originally stated that more restrictive models are easier to understand. My point is not that they never are (as in some universal truth). It's that the real answer is that it depends. And, in the context of this discussion, simply declaring that the restrictions that immutability imposes are automatically beneficial to understanding is a non-sequitur.
But, WRT to the specifics you provided, your model may indeed provide structure that can aid in understanding the code. But, I don't think it's the degree of restrictiveness that determines this, as much as that there is some model in the first place. Of course, whether it's the best choice in a given situation is a relative proposition.
Interestingly, however, you allow for mutability. And the real "magic" is happening not through immutability alone, but careful assignment of mutability operations in conjunction with other concurrency idioms that you expect to overlay atomicity.
So, essentially we agree: declaring mutability as the root of all evil is overkill. Instead, the real prescription relies upon carefully considered/managed mutability, used with the language's intended concurrency features.
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.
data class Foo(bar: String, baz: String)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