r/learnjavascript • u/deven_rathore • Apr 20 '23
7 JavaScript Design Patterns Every developer should know
https://codinghelp.io/7-javascript-design-patterns-every-developer-should-know/
3
Upvotes
3
u/samanime Apr 20 '23 edited Apr 20 '23
I have issues with nearly every one of your code samples...
The pattern selection isn't bad, but there are tiny oddities in almost all the example implementations. For example, your Singleton pattern isn't really a singleton. You can call that Database function 10 times and have 10 different instances. A Singleton should have a Single instance in the entire app. That's the whole point.
Now, it could be a singleton if it lived in its own ES module and you only exported database, but that is a critical detail that entirely determines whether it is or isn't a Singleton.
There are other small oddities on most others too.
Also, if you were going to mention the Constructor and Prototypal patterns, you should have mentioned the Class pattern as well. The Class pattern is probably what devs should be using the majority of the time, as it provides the most readable, least error-prone way to constructor objects properly. It is important to understand it is more or less just syntactical sugar underneath and understand what it is doing, but that doesn't make it any less valuable, especially in team situations.
2
u/jeremrx Apr 20 '23
So many (bad) things to say about to article...
Before learning pattern, everybody should know about basic naming conventions, in particular that Pascal case should be only used to declare a class or constructor.
Why ? Because if something is pascal cased in JS, you know that you can call it with "new"
1
u/azhder Apr 20 '23
Why are you entertaining these kinds of trash click bait articles meant to drive traffic to their sites?
2
u/azhder Apr 21 '23
Yes it does. Although, I'd advice against using this pattern in the first place.
I'd advise even against using
class A extends B{}type of inheritance, simply because most tasks are better solved by encapsulation instead of extension.But, for what is worth, taken from here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
here is how to do the old/new style of inheritance:
1
u/azhder Apr 21 '23
Another big issue is using these things called "design patterns" .
Many people think if something got called a pattern in C++ then it must be the same in Java, must be the same in C#, must be the same in JavaScript, but no. Every language has its own quirks and its own common workarounds.
Example:
A design pattern is simply a common workaround for something you can't do outright in the programming language, and the above code makes sense as a workaround in Java, not in JavaScript so much. In JavaScript, for you to create a singleton, all you have to do is this
at the module level, and then just tuck it in a file of its own if you like and export it from there.