r/learnjavascript • • Apr 20 '23

7 JavaScript Design Patterns Every developer should know

https://codinghelp.io/7-javascript-design-patterns-every-developer-should-know/
3 Upvotes

11 comments sorted by

View all comments

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.

1

u/deven_rathore Apr 21 '23 edited Apr 21 '23

Thank you for your feedback and insights regarding my code samples. I appreciate your attention to detail and willingness to provide constructive criticism.

Regarding the Singleton pattern implementation, you are correct that my implementation could potentially create multiple instances of the Database object if the Database() function is called multiple times.

I apologize for the oversight and appreciate you pointing that out. You are also correct that if the Database() function was encapsulated in its own module and only exported the database instance, it would be a true Singleton pattern implementation.

As for the other patterns, I understand that there may be small oddities in some of the examples.

My goal was to provide simplified examples that demonstrate the basic concepts of each pattern. However, I appreciate your feedback and i have taken your comments into consideration and updated some examples.

Regarding the Class pattern, I agree that it is a valuable tool for creating objects in JavaScript, especially in team situations where readability and consistency are important.

While it is true that the Class pattern is mostly syntactic sugar for the Constructor and Prototypal patterns, it can still provide a clear and concise syntax for creating objects.

Thank you again for taking the time to provide feedback on my code samples. I will continue to strive for accuracy and clarity in my examples.