DEV Community

Discussion on: Replacing JavaScript Classes With The Module Design Pattern

Collapse
 
bytebodger profile image
Adam Nathaniel Davis • Edited

Of course I totally agree with you. As a bit of further clarification/distillation, I'll summarize my recent turn toward MDP like this:

  1. React is my main focus (for now, at least - it tends to change every few years or so). Once React started moving much stronger to functions/Hooks, I found that nearly all of my React code looks much more like this pattern anyway. Maybe, when I'm writing a bunch of non-React stuff, I'll float back toward class. But for right now, it's easy to keep a consistent style across all my code.

  2. As outlined in the article, I do think there's one key benefit to this pattern over class - mainly, that it's somewhat "cleaner" and more intuitive to create private members. IMHO, that's not inconsequential. I find that many JS devs rarely even think about design patterns with regard to private variables, because the language doesn't make it easy for them to conceptualize them (like, for example, having a handy little private keyword available). So they rarely think about things like having protected access to update a variable. I've seen far too many instances where someone spins up a variable, alongside the variable's setter, and then they pass that setter around knowing dang well that the app will BREAK if that variable gets set to the "wrong" kind of value. Of course, this pattern doesn't fix that problem. But I do think it makes it easier to avoid it.

  3. Finally, this is absolutely a bit of a white flag on my part. The syntax I've shown above is something I'm perfectly comfortable with (again, because I'm a React dev). And as you've pointed out, the syntax above is truly just another version of what we get with class. But to be perfectly frank with you, if I can do something in two different ways, and I'm perfectly comfortable with both of those ways, but one of those ways will spawn an endless stream of petty squabbles from ill-informed language purists??? Well...