Immutability changes everything, part CXXVIII

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

Interesting:

If I had to give a single reason to use Clojure, it would be this: immutability is awesome. It protects you from yourself in ways that aren’t immediately obvious at first, but become more apparent over time.

The argument that follows is particularly catered to the world of web development, but remains applicable in other contexts as well.

In short: application state is a source of complexity, and unwarranted complexity is a developer’s worst enemy. This is true on the basic level of single-process, single-threaded programs, and becomes increasingly more so as both thread and process count increase.

Coming from a background in mutable languages, some degree of application state just seems like the cost of doing business – after all, how else to track changes to business objects over time? The answer’s pretty straightforward, actually – just push state management into your database.

If that sounds like passing the buck, that’s because it is, but that’s okay – unless you’re running a very particular type of application, odds are you’re already using your database as an engine of state; you’re just also using your application layer. The thing is, the semantics of database transactions for the purpose of state management are well studied, with the result that most production-level database technologies don’t risk the sort of bugs that one encounters by trying to handle state in an application, let alone in an application being run in a distributed environment.

Ultimately, pushing state into the database works because most web applications rarely need to hold onto a particular object for very long, and functional languages like Clojure make it easy to pass values around and to track modifications made to them without mutating the underlying data structures.

There are, of course, times when you really do need a mutable object, and Clojure has types for them as well. They’re definitely used, but less frequently than one would think.

I have a lot of trouble overstating the value proposition of immutability, particularly when I’m talking to people whose only reference point is a mutable environment. The only thing I can say is that after a few months of writing Clojure code I couldn’t help but notice that an entire class of bug had simply vanished from my regular development flow.

Post external references

  1. 1
    http://blog.venanti.us/why-clojure/
Source