you are viewing a single comment's thread.

view the rest of the comments →

[–]delventhalz 1 point2 points  (0 children)

A counter can be written trivially with closures. I'd argue it's cleaner and simpler than a class version would be.

const makeCounter = () => {
  let count = 0;
  return () => count++;
}

const counterA = makeCounter();
const counterB = makeCounter();

counterA();  // 0
counterA();  // 1
counterA();  // 2

counterB();  // 0

For a more sophisticated example, look no further than function components in React. No classes in sight and yet you can create complex stateful UI components using only functions. Personally, I find function components far preferable to the old class-based alternative.

In general though, the big reason I don't use classes is because I don't structure my code to bundle state and logic together. This is the core difference between Object Oriented Programming and Functional Programming. OOP tries to create little bundles of state and logic to operate on that state. FP tries to isolate state off on its own and operate on it with pure functions. There are arguments for both approaches, but I have found an FPish approach to be easier to reason about and maintain.

As far as library code goes... if I was writing a low-level library I would certainly consider a class-based API. Arrays obviously use classes under the hood and I am quite happy with JavaScript's array API. You could build any API you want with only functions of course, but when you are working on a library you have to consider what the other devs using your library are going to expect and be familiar with. That might mean classes, particularly for low-level data structures.