Hacker News new | ask | show | jobs
by oh-4-fucks-sake 1662 days ago
Kotlin has been a godsend when it comes to breaking free of Java dogmatic thinking. The effort to write good functional code is so much less. That's not to say that classes are useless. I try to limit class usage to data structures that do no more than:

- Store data

- Simple convenience functions that tell me about its state

- Side-effect-free mutations (or data massaging) that have no external dependencies other than function params

- Simple validation, if there are no external dependencies

Everything else goes in a service/function.

1 comments

Classes manage something stateful.

One anti-pattern/code smell I often see is finding classes in a service which should just be a functionally pure pipeline (eg. no internal state is managed)

Agreed. Exception here is when you're making the trade-offs to buy into a DI framework--which you could argue is a descendent need from the "everything is a class" worldview. Pure/dependency-free util functions can very naturally live outside of all of this. But, the minute you have functions that depend on inherently stateful infrastructure (e.g. datasource connections--so, most applications), then those functions become inherently stateful--which makes them less natural to exist as pure utils and starts to make DI more attractive--which leads us back to placing pipeline code within classes. Alternatively, you could expose only the stateful pipeline code within singletons, but at some point you start to fight the community patterns--which means you start to lose out on community goodies. To be clear, this is all only based my experiences and I'm not dogmatic at all about any of this. Times change/everything-old-is-new-again. I'm sure classes will make a comeback, and then go out of favor again--as is life.