DEV Community

Ski
Ski

Posted on

Classes are still useful even in largely functional style code

It’s became a fashion to rid code of classes even when it doesn’t help produce better code. The popular web UI framework React is likely a culprit — so many developers are familiar with React and so any trends started by React developers inevitably spread even if outside React same concepts don’t work at all.

While classes are mostly associated with object oriented programming they can also be just as useful tool in functional programming as they are in OOP. Functional programming while containing useful ideas and goals badly lacks down to earth vocabulary.

The use case that classes solve is same that of “Higher-order functions”. This functional term is a bit broad — it’s good to describe a general approach but not good to name the individual bits in code. It’s not immediately clear if higher-order function refers to function that returns a function, or a function that takes a function as a parameter or a function that has been returned by a function and in this sentence the word function was used so many times that it should be pretty clear that we need better vocabulary.

Classes provide more structure and very useful vocabulary:

  • Class
  • Constructor
  • Instance
  • Property
  • Method

Now it’s easy to identify what is what — instead of “function that returns a function” — we got a “class" and "constructor”. Instead of “function that has been created inside a function” — we have a method. And it has became explicit that methods don’t exist without instances, just like returned functions don’t exist without hidden closures attached to them.

What also very helpful is that classes and instances are always nouns. This makes code look more like a human language — we humans do not receive verbs as gifts on birthdays. Meanwhile typically verbs are frequently used to name functions thus it often becomes awkward to give names to variables that hold on to functions.

What classes help to achieve — a code written in such a manner that all functions are always verbs, and all things that can be passed around are always nouns. It helps to achieve consistency. It helps to talk about code. And yes it’s sometimes takes more time to give meaningful naming — but this is a good problem to have — after it’s solved it creates a code that is more easy to understand and has more clearly defined structural shape.

It doesn’t matter if you’re fan of functional programming or not — if your programming language has classes — use them instead of just plain functions — it’s good for your code.

Discussion (0)