2021.04.09 Writers vs. Functional Programming - GlenKPeterson/One-off_Examples GitHub Wiki

Java had Writer classes which were a really cool thing in the 1990's. I used to write a lot of methods like this:

void showThing(WriterOrBuffer o, otherParams...) {
    o.write(...);
    o.write(...);
    o.write(...);
}

Basically, pass it a writer or a buffer, and it will stick the appropriate data into it and return void. Advantages:

  • It can handle any size output (if the Writer or Buffer is constructed well).
  • A writer can use very little memory by writing to disk or network as often (or as rarely) as necessary.
  • You can generally write code that you can pass either a writer or a buffer to, and it will just work.
  • It may be faster than the immutable version, IDK.

Aside about mutability

A rarely appreciated aspect of Writers is that they are write-only. We hear all about Immutability and read-only data structures because they are stateless - yay! But Writers, though internally stateful, are safe in their own way because (at least in Java) they are generally write-only data structures. There's no methods to query the internal state. It's all sticking data into the writer and the writer just does its thing. The state is effectively encapsulated, making it "safe" in much the same way Immutable data structures are safe. At least until something goes wrong, like an IOException.

The Problems

Testing

It's just so darn simple to test pure functions.

Composition

Pure functions tend to be more composable and reusable. Much better to return a data structure that can be used for various purposes than to disappear data down some hole to a file or network connection.

Readability

Once you start throwing data down a write-only hole, your code develops a different kind of smell. It feels... hasty somehow. Like you can just mutate anything and damn the consequences! A little of this is OK, but it's a slippery slope to an unmaintainable mess.

Conclusion

If you're likely to deal with data too big to fit in memory, writers may be the way to go. I just don't seem to often be in that situation any more. Not sure if I ever was.

Whole books are being written about the joys of immutabile, reusable data: https://www.manning.com/books/data-oriented-programming It's a Thing now. Java's approach is a type-safe one, so a little different, but immutable data structures tend to be reusable, but throwing data down a write-only hole is not. I now prefer pure functions that return data structures.