-
Notifications
You must be signed in to change notification settings - Fork 0
2021.04.09 Writers vs. Functional Programming
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
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.
It's just so darn simple to test pure functions and compose them for various purposes.