
Want Clean Code? Just Use Functions.
Earlier on in my programming career, I got pretty heavy into Object-Oriented Programming and all the various design patterns around it (there are a lot). I used to worship at the alter of Martin Fowler and zealously look for opportunities to implement all of the various Gang of Four Design Patterns into my codebases. Looking back, it was a huge mistake and a huge waste of time. While some design patterns are useful in certain situations (like the adapter pattern!), going deep down the OOP rabbit hole made my code less readable, more verbose, less maintainable, and less flexible for future changes.
The best advice I can give new programmers now is: Just use functions. Mostly pure. Well named and organized. Each with a single purpose. That’s it. You don’t need tons of classes or objects. You don’t need to encapsulate all your data in some object with getters and setters. You don’t need a Registry or a Dependency Injection Container with Inversion of Control. Just. Use. Functions.
Just Use Functions
In JavaScript/TypeScript, using only functions is incredibly easy. Create modules with exported named functions that are well-named and single-purpose.
A popular (and correct!) quote on the complexity of Object-Oriented code:
I think the lack of reusability comes in object-oriented languages, not functional languages. Because the problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but what you got was a gorilla holding the banana and the entire jungle.
If you have referentially transparent code, if you have pure functions — all the data comes in its input arguments and everything goes out and leave no state behind — it’s incredibly reusable.
– Joe Armstrong, creator of Erlang
For the code itself, just use functions! For larger architecture efforts, focus most of your time on data structures and data storage patterns instead of trying to model it in code with objects. If you ever need the code in a different format or shape than you store it in, write a transform function that you run it through first instead of layers of OOP abstraction. Your future self – and your future team – will thank you.
Categories: Opinion, Programming, Software