Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Singleton Pattern? No! Use this instead 💡

Posted on Sep 27 The Singleton Pattern is extremely popular among beginners in Object-Oriented Programming due to its ease of implementation and promise of global state handling, but is it worth it?Simply put, the Singleton Pattern ensures that a class has only one instance while providing a global access point to that instance. You can imagine that it could be useful to share a configuration object across an application, for example.To create a singleton, we will need to add a couple of things to our class:Let's check the full code in Java to visualize it better:We can check if it is working with the following:Note that we didn't directly instantiate it.Here, both singleton1.value and singleton2.value would have the same value "PIPIPI" because the object was created on the first call only, and the second one can only access the cached object.That's it! Well... it depends.This implementation particularly is too simplistic for multi-threaded languages like Java because different threads could create different instances simultaneously, so it would not be a Singleton anymore, right? If we need some sort of slow initialization, we will run into problems.To prevent race conditions like that we need to synchronize threads when instantiating the singleton. I won't get into details here because the solution requires double-checked locking and that's another topic. Also, Java handles it in its very own way and it requires some extra knowledge.Refactor Guru provides a very interesting implementation of a thread-safe singleton and explains pretty well the strategy behind double-checked locking. Check it out for further discussion.Our class is breaking the Single Responsibility Principle by trying to solve two problems at the same time: Ensure that it is instantiated only once and provide a global access point to that instance.A class exists to serve as a blueprint of an object, and not to also instantiate the object itself.Since we use Singletons to expose global state, it makes no sense to inject them into other objects, right? But with this approach you end up hiding the dependencies of your application in your code, instead of exposing them through interfaces, and we should code against interfaces, not implementations.Without dependency injection, our singletons and the classes that need him are tight-coupled, creating a huge problem when unit testing.Also known as BorgIdiom (because the Borgs in the Star Trek series share a common memory), the Monostate Pattern allows the creation of multiple objects that share the same static attributes instead of guaranteeing that only a single instance of a class exists.Both values will be "Banana" but monostate1 == monostate2 will be false, because they are not the same object.Monostate has one major advantage over singleton: The subclasses might decorate the shared state as they wish and hence can provide dynamically different behavior than the base class.Users of a monostate do not behave differently than users of a regular object. The users do not need to know that the object is monostate, and that's one of the most important characteristics.Sharing the same state across an application and expose an API to modify it, can very easily lead to confusion since it gets almost impossible to know what is the current value once the setter is called in different places.Let's re-create the first Singleton example with a setter, so we can assign a new value not only in the constructor but anytime.For the sake of simplicity, the example is all in the entry point of the app:Both print "POPOPO" because there is only one instance! So if we have a singleton3, singleton4, and so on (or simply Singleton. You don't need to assign a static class to a new variable) anywhere in our app, it's really difficult to keep track of our current state value.It is even worse if the value type is a reference type like an Array, ArrayList, or any Iterable! Just think about the number of nullPointerExceptions that it could create, or the unexpected elements inside.On that matter, I honestly believe functional programming brings a better approach with the use of pure functions, but that's a discussion for the future.We cannot use a design pattern blindly. It can solve a problem while creating others if we don't have an understanding of the pros and cons.Also, SOLID principles are not sacred but they've been tested over decades and developed conventions proven to create better maintainability for huge codebases, so I particularly tend to respect them a lot for the code quality they brought to my career.Thank you so much for reading.https://refactoring.guru/design-patterns/singletonhttps://www.freecodecamp.org/news/solid-principles-explained-in-plain-english/https://www.youtube.com/watch?v=yimeXZ1twWshttps://stackoverflow.com/questions/137975/what-are-drawbacks-or-disadvantages-of-singleton-patternhttps://jorudolph.wordpress.com/2009/11/22/singleton-considerations/https://betterprogramming.pub/code-against-interfaces-not-implementations-37b30e7ab992https://www.simplethread.com/the-monostate-pattern/Templates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Nijit Krishna Hazarika - Sep 14 Scofield Idehen - Sep 25 DR - Sep 18 Leetcode - Sep 13 Once suspended, gabrielprrd will not be able to comment or publish posts until their suspension is removed. Once unsuspended, gabrielprrd will be able to comment and publish posts again. Once unpublished, all posts by gabrielprrd will become hidden and only accessible to themselves. If gabrielprrd is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to Gabriel Afonso. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag gabrielprrd: gabrielprrd consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging gabrielprrd will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

Singleton Pattern? No! Use this instead 💡

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×