Benefits of Functional Collections ¶
The case for using functional collections is much better known now than it was in 2007, when I first
released FSet. Rich Hickey made his first release of Clojure the same year; his design also
embraced functional collections, and its popularity has done much to make programmers aware of their
advantages. Those include:
- Clearer, more elegant code:
Code written in a functional style is often easier to understand than code involving shared state,
because to understand what a given expression does, you only need to know what operation it’s
performing and what the argument values are. The data flow is all made explicit; no other state of
the program is relevant.
- Concurrency safety:
Reading from functional collections is thread-safe without locking, as is iteration. Iteration is
also safe from concurrent updates in the same thread. While read-update-write operations still
require synchronization, Software Transactional Memory can be used instead of locking, potentially
improving parallelism.
- Persistence:
The term “persistent”, in this context, refers to data structures that can efficiently retain
their past states; it has nothing to do with the use of nonvolatile storage. Persistent functional
collections can be used to easily implement “undo” functionality; all that’s needed is to retain
the past states one might want to return to.
- Cleaner interfaces:
Functional collections can be returned from interfaces with no concern that the client might modify
them, breaking the module that owns them; defensive copying against this possibility is not required
either.
- Easier testing:
Functional code is generally easier to test and debug, because once you have appropriate arguments
constructed, you can call the function in question any number of times, without it altering state
that you would have to reset.
My strong opinion is that functional collections are the best default choice for the vast
majority of programming tasks: the kind everyone should be using except in the very few cases in
which performance concerns dictate a different choice. Furthermore, language and library designers
should support the movement toward functional collections by providing high-quality implementations.
FSet is my contribution to this effort.