DEV Community

Ski
Ski

Posted on • Updated 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 it's more natural to name classes using nouns. This makes code look more like a human language - we typically don't use verbs to describe gifts that we get on birthdays. Meanwhile typically verbs are frequently used to name functions/methods thus it often becomes awkward to give a name to variables that hold on to a function that's bound to closure. On one hand it makes sense that function is verb on other hand when function is passed around like a gift it's awkward if it's name is a verb.

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.

Oldest comments (0)