SlideShare a Scribd company logo
1 of 36
Download to read offline
Singleton
The Perks and Perils of the Singleton Design Pattern
Motivation
You have that one, and exactly one object:
● Database connection
● Hardware interface
● …
and you have to make sure all parts of the application use
that one and only object
Solution
Head up to that class, and:
● Restrict the class to create only one object
● Provide global access to it
Ref: [1]
Example Single Instance
Global Access
Use it anywhere
View 1
View 2
Users Store
Some object
Example - Diagram
Example - Even more!
View 1
View 2
View 3
Users Store
Departments
Store
Singletons
(DB /
Backend)
Connection
Techniques
Lazy initialization
Ref: [2]
Techniques 2
Synchronized lazy initialization
Clearer, but lower concurrency
Higher concurrency
Ref: [2]
Techniques - 3
Eager initialization
No need for synchronization
Ref: [2]
Benefits
● State shared globally as required
● Global access; No complications to object access
● The object handles its own creation logic
● Hide details of the Singleton
● Can be used to implement some other patterns as well
○ Abstract Factory, Builder, Prototype …
The end
Not really!
Singleton as an anti-pattern
Singleton is popular because:
● It was included in GoF Design Patterns
● It’s easy; the easiest in the book
People started a rebellion:
● Any design pattern can be abused, except for Singleton
● Valid motive, but ruins everything with its two steps
Ref: [3, 10]
Glorified Global Variables
Have a bug? Now go over all those files for a clue!
Mutable
state
1
This one
caused the
bug
2
This one
found it
Ref: [4]
Glorified Global Variables
When some code uses a global variable, it’s harder to
reason about it
Mutable
state
1
To know what this
object / function is
doing
2
You also
need to
understand
what this is
doing
Ref: [4]
Lifecycle
The Singleton controls its own creation and lifecycle
● Violation of SRP:
○ Connecting to database is a responsibility
○ Creating, opening and closing the connection are other
responsibilities
● Resetting the state is harder and more error-prone
than creating a new object
Ref: [3, 5]
Lifecycle
● Now you have to make all
Singletons reset to initial state
● You have to wait to reset
properly
○ Sync data
○ Clear cache
Lifecycle
● The user’s signed-in session is shorter than the
application’s lifecycle.
● A global state, if necessary, should only handle states
that last for the entire application’s complete lifecycle
Ref: [5]
Hiding Dependencies
● You don’t know what that Singleton needs
○ Singleton.getInstance() doesn’t explain much
Data List Singleton
What you see
Data List Singleton
What it actually is
Connection Authenticator
User
Ref: [3]
Hiding Dependencies - Example
● Only works when you run as
part of the suite.
● When run in isolation,
throws
NullPointerException.
Ref: [3]
Hiding Dependencies - Example
● You ask a senior, and he tells
you that CreditCardProcessor
needs to be handled first
● Still, it throws an exception
Ref: [3]
Hiding Dependencies - Example
● You ask more. Now you know
that both Database and
OfflineQueue need to be
initialized first
● The code worked!
● Now your bank account only
has $12.5 because this code
charged you for $100
Must be done
in the same
order!
Ref: [3]
● The code is not stable, if Database gets modified,
other classes may fail
○ Because you don’t know what depends on Database and how
● The code is not flexible, anything that depends on a
Singleton is hard wired to that Singleton
● You can’t unit test a class without the Singleton
initialized
● You can’t use mock objects for testing
Hiding Dependencies
Ref: [3]
Encourage Coupling
● Since it’s global, any class anywhere can get it easily
● If the developer is thinking hard how to get it in that
class, he would think if that class should get it
Coupling between SomeTransaction
and MySQLConnection
Ref: [4]
Encourage Coupling
● Now, you need to use a NoSQL database along with the
SQL one
● SomeTransaction should switch to NoSQL database
SomeTransaction
MongoDBConnection
MySQLConnectionTightly coupled
Remove the coupling
between
SomeTransaction and
MySQLConnection first
Limiting Instantiation
Are you really sure you won’t need another object of that
Singleton class?
nobacks.com
SingletonScreen
We only need
one object for
that one screen
nobacks.com
So what happens when I plug
that screen to the laptop?
Big deal!
I don’t care if they’re bad or not.
I only use one or two Singletons,
what’s going to happen anyway?
Source
That’s the real problem!
This one or two Singletons are strangling all or most of
classes
○ Many classes are tightly coupled to it
○ Many classes can’t be tested properly
○ Change something in that Singleton and all other classes need
to be changed as well
The Root of the Problem
This part is
very
legitimate!
This is
not
Ref: [9]
Solution
● Pass it a.k.a “Inject it!”
● Get it from somewhere already global
○ That place is responsible for creating it and managing its
lifecycle
○ There are some evils that we can only reduce, but can never
eliminate, like global state
Ref: [7]
Example
A whole bunch of singletons
Ref: [7]
Example
new OfflineQueue(database)
Ref: [7]
Example
● We’re sure that only one object is being used
● Dependencies are declared
● Dependencies are passed
● Each class is testable and mockable
● “Creation” is the factory’s responsibility
● If you ever need to have a new database, you don’t
have to modify available classes
Ref: [7]
Immutable State Singletons
Immutable state Singletons, enums in Java, objects in
Scala, … are okay
But still, be aware of coupling, limiting classes from
inheritance, hiding dependencies …
Ref: [9]
References
1. c2.com: Singleton
2. Wikipedia
3. SO: What's so bad about singletons
4. gameprogrammingpatterns.com
5. Avoiding Singleton Abuse
6. programmers.stackexchange: So singletons are bad then what
7. Singletons are pathological liars
8. Where have all the singletons gone
9. Root cause of singletons
10. Singletons considered stupid
Questions?

More Related Content

Viewers also liked

Tema 4 los seres vivos
Tema 4 los seres vivosTema 4 los seres vivos
Tema 4 los seres vivospgp3
 
Las tic nadia liliana mina bedoya.pptx28
Las  tic nadia liliana mina bedoya.pptx28Las  tic nadia liliana mina bedoya.pptx28
Las tic nadia liliana mina bedoya.pptx28nadialilianaminabedoya
 
Cuandotodopareceperdido
CuandotodopareceperdidoCuandotodopareceperdido
Cuandotodopareceperdidoyolis0223
 
Pristolepis pentacantha, a new species
Pristolepis pentacantha, a new speciesPristolepis pentacantha, a new species
Pristolepis pentacantha, a new speciesMathews Plamoottil
 
Investigación Cuantitativa
Investigación Cuantitativa Investigación Cuantitativa
Investigación Cuantitativa Aracely Castillo
 
Central asia adventure tours
Central asia adventure toursCentral asia adventure tours
Central asia adventure toursAsiaAdventures
 
Antibody Aducanumab Reduces Αβ Plaques in Alzheimer’s Disease
Antibody Aducanumab Reduces Αβ Plaques in Alzheimer’s DiseaseAntibody Aducanumab Reduces Αβ Plaques in Alzheimer’s Disease
Antibody Aducanumab Reduces Αβ Plaques in Alzheimer’s DiseaseRiaz Rahman
 
InnoVision Fall 2016
InnoVision Fall 2016InnoVision Fall 2016
InnoVision Fall 2016Sarah Berry
 
Mi semana de nuevas tecnologias!!
Mi semana de nuevas tecnologias!!Mi semana de nuevas tecnologias!!
Mi semana de nuevas tecnologias!!FELIPE MENDO LÓPEZ
 

Viewers also liked (13)

Webquest
WebquestWebquest
Webquest
 
Unidad iii estrategias didacticas
Unidad iii estrategias didacticasUnidad iii estrategias didacticas
Unidad iii estrategias didacticas
 
Tema 4 los seres vivos
Tema 4 los seres vivosTema 4 los seres vivos
Tema 4 los seres vivos
 
Las tic nadia liliana mina bedoya.pptx28
Las  tic nadia liliana mina bedoya.pptx28Las  tic nadia liliana mina bedoya.pptx28
Las tic nadia liliana mina bedoya.pptx28
 
Cuandotodopareceperdido
CuandotodopareceperdidoCuandotodopareceperdido
Cuandotodopareceperdido
 
Pristolepis pentacantha, a new species
Pristolepis pentacantha, a new speciesPristolepis pentacantha, a new species
Pristolepis pentacantha, a new species
 
Investigación Cuantitativa
Investigación Cuantitativa Investigación Cuantitativa
Investigación Cuantitativa
 
Central asia adventure tours
Central asia adventure toursCentral asia adventure tours
Central asia adventure tours
 
Antibody Aducanumab Reduces Αβ Plaques in Alzheimer’s Disease
Antibody Aducanumab Reduces Αβ Plaques in Alzheimer’s DiseaseAntibody Aducanumab Reduces Αβ Plaques in Alzheimer’s Disease
Antibody Aducanumab Reduces Αβ Plaques in Alzheimer’s Disease
 
InnoVision Fall 2016
InnoVision Fall 2016InnoVision Fall 2016
InnoVision Fall 2016
 
Mi semana de nuevas tecnologias!!
Mi semana de nuevas tecnologias!!Mi semana de nuevas tecnologias!!
Mi semana de nuevas tecnologias!!
 
CORPORATE_MIPCOM
CORPORATE_MIPCOMCORPORATE_MIPCOM
CORPORATE_MIPCOM
 
Tutorial Viadeo
Tutorial ViadeoTutorial Viadeo
Tutorial Viadeo
 

Similar to The Perks and Perils of the Singleton Design Pattern

Android Frameworks: Highlighting the Need for a Solid Development Framework 
Android Frameworks: Highlighting the Need for a Solid Development Framework Android Frameworks: Highlighting the Need for a Solid Development Framework 
Android Frameworks: Highlighting the Need for a Solid Development Framework Mutual Mobile
 
Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Ramith Jayasinghe
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad WoodOrtus Solutions, Corp
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design PatternsRobert Brown
 
Handling Lifecycles in a Jetpack way
Handling Lifecycles in a Jetpack wayHandling Lifecycles in a Jetpack way
Handling Lifecycles in a Jetpack wayHan Yin
 
Why React's Awesome!
Why React's Awesome!Why React's Awesome!
Why React's Awesome!nomanalikk
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Grzegorz Miejski
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfKnoldus Inc.
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxanguraju1
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in PythonRyan Johnson
 
O365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialO365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialThomas Daly
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type scriptRavi Mone
 
Create first android app with MVVM Architecture
Create first android app with MVVM ArchitectureCreate first android app with MVVM Architecture
Create first android app with MVVM Architecturekhushbu thakker
 
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...Codemotion
 
Angular Rebooted: Components Everywhere
Angular Rebooted: Components EverywhereAngular Rebooted: Components Everywhere
Angular Rebooted: Components EverywhereCarlo Bonamico
 
Application Development Using Java - DIYComputerScience Course
Application Development Using Java - DIYComputerScience CourseApplication Development Using Java - DIYComputerScience Course
Application Development Using Java - DIYComputerScience Courseparag
 

Similar to The Perks and Perils of the Singleton Design Pattern (20)

Android Frameworks: Highlighting the Need for a Solid Development Framework 
Android Frameworks: Highlighting the Need for a Solid Development Framework Android Frameworks: Highlighting the Need for a Solid Development Framework 
Android Frameworks: Highlighting the Need for a Solid Development Framework 
 
Why Concurrency is hard ?
Why Concurrency is hard ?Why Concurrency is hard ?
Why Concurrency is hard ?
 
Concurrency - Why it's hard ?
Concurrency - Why it's hard ?Concurrency - Why it's hard ?
Concurrency - Why it's hard ?
 
cf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Woodcf.Objective() 2017 - Design patterns - Brad Wood
cf.Objective() 2017 - Design patterns - Brad Wood
 
Mac/iOS Design Patterns
Mac/iOS Design PatternsMac/iOS Design Patterns
Mac/iOS Design Patterns
 
Handling Lifecycles in a Jetpack way
Handling Lifecycles in a Jetpack wayHandling Lifecycles in a Jetpack way
Handling Lifecycles in a Jetpack way
 
Design_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.pptDesign_Patterns_Dr.CM.ppt
Design_Patterns_Dr.CM.ppt
 
Making Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF UsableMaking Strongly-typed NETCONF Usable
Making Strongly-typed NETCONF Usable
 
Why React's Awesome!
Why React's Awesome!Why React's Awesome!
Why React's Awesome!
 
Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019Tests immutable when refactoring - SegFault Unconference Cracow 2019
Tests immutable when refactoring - SegFault Unconference Cracow 2019
 
Basics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdfBasics of React Hooks.pptx.pdf
Basics of React Hooks.pptx.pdf
 
UNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptxUNIT IV DESIGN PATTERNS.pptx
UNIT IV DESIGN PATTERNS.pptx
 
Async Web Frameworks in Python
Async Web Frameworks in PythonAsync Web Frameworks in Python
Async Web Frameworks in Python
 
O365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - MaterialO365 Developer Bootcamp NJ 2018 - Material
O365 Developer Bootcamp NJ 2018 - Material
 
Angular2 with type script
Angular2 with type scriptAngular2 with type script
Angular2 with type script
 
Create first android app with MVVM Architecture
Create first android app with MVVM ArchitectureCreate first android app with MVVM Architecture
Create first android app with MVVM Architecture
 
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
Angular Rebooted: Components Everywhere - Carlo Bonamico, Sonia Pini - Codemo...
 
Angular Rebooted: Components Everywhere
Angular Rebooted: Components EverywhereAngular Rebooted: Components Everywhere
Angular Rebooted: Components Everywhere
 
Frontend training
Frontend trainingFrontend training
Frontend training
 
Application Development Using Java - DIYComputerScience Course
Application Development Using Java - DIYComputerScience CourseApplication Development Using Java - DIYComputerScience Course
Application Development Using Java - DIYComputerScience Course
 

More from BADR

Sunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into SolrSunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into SolrBADR
 
Docker up and Running For Web Developers
Docker up and Running For Web DevelopersDocker up and Running For Web Developers
Docker up and Running For Web DevelopersBADR
 
Vue.js
Vue.jsVue.js
Vue.jsBADR
 
There and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming LanguagesThere and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming LanguagesBADR
 
Take Pride in Your Code - Test-Driven Development
Take Pride in Your Code - Test-Driven DevelopmentTake Pride in Your Code - Test-Driven Development
Take Pride in Your Code - Test-Driven DevelopmentBADR
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility PrincipleBADR
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL DatabasesBADR
 
Explicit Semantic Analysis
Explicit Semantic AnalysisExplicit Semantic Analysis
Explicit Semantic AnalysisBADR
 
Getting some Git
Getting some GitGetting some Git
Getting some GitBADR
 
ReactiveX
ReactiveXReactiveX
ReactiveXBADR
 
Algorithms - A Sneak Peek
Algorithms - A Sneak PeekAlgorithms - A Sneak Peek
Algorithms - A Sneak PeekBADR
 
Android from A to Z
Android from A to ZAndroid from A to Z
Android from A to ZBADR
 
Apache Hadoop - Big Data Engineering
Apache Hadoop - Big Data EngineeringApache Hadoop - Big Data Engineering
Apache Hadoop - Big Data EngineeringBADR
 
MySQL Indexing
MySQL IndexingMySQL Indexing
MySQL IndexingBADR
 
Duckville - The Strategy Design Pattern
Duckville - The Strategy Design PatternDuckville - The Strategy Design Pattern
Duckville - The Strategy Design PatternBADR
 

More from BADR (15)

Sunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into SolrSunspot - The Ruby Way into Solr
Sunspot - The Ruby Way into Solr
 
Docker up and Running For Web Developers
Docker up and Running For Web DevelopersDocker up and Running For Web Developers
Docker up and Running For Web Developers
 
Vue.js
Vue.jsVue.js
Vue.js
 
There and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming LanguagesThere and Back Again - A Tale of Programming Languages
There and Back Again - A Tale of Programming Languages
 
Take Pride in Your Code - Test-Driven Development
Take Pride in Your Code - Test-Driven DevelopmentTake Pride in Your Code - Test-Driven Development
Take Pride in Your Code - Test-Driven Development
 
Single Responsibility Principle
Single Responsibility PrincipleSingle Responsibility Principle
Single Responsibility Principle
 
NoSQL Databases
NoSQL DatabasesNoSQL Databases
NoSQL Databases
 
Explicit Semantic Analysis
Explicit Semantic AnalysisExplicit Semantic Analysis
Explicit Semantic Analysis
 
Getting some Git
Getting some GitGetting some Git
Getting some Git
 
ReactiveX
ReactiveXReactiveX
ReactiveX
 
Algorithms - A Sneak Peek
Algorithms - A Sneak PeekAlgorithms - A Sneak Peek
Algorithms - A Sneak Peek
 
Android from A to Z
Android from A to ZAndroid from A to Z
Android from A to Z
 
Apache Hadoop - Big Data Engineering
Apache Hadoop - Big Data EngineeringApache Hadoop - Big Data Engineering
Apache Hadoop - Big Data Engineering
 
MySQL Indexing
MySQL IndexingMySQL Indexing
MySQL Indexing
 
Duckville - The Strategy Design Pattern
Duckville - The Strategy Design PatternDuckville - The Strategy Design Pattern
Duckville - The Strategy Design Pattern
 

Recently uploaded

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 

Recently uploaded (20)

The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 

The Perks and Perils of the Singleton Design Pattern

  • 1.
  • 2. Singleton The Perks and Perils of the Singleton Design Pattern
  • 3. Motivation You have that one, and exactly one object: ● Database connection ● Hardware interface ● … and you have to make sure all parts of the application use that one and only object
  • 4. Solution Head up to that class, and: ● Restrict the class to create only one object ● Provide global access to it Ref: [1]
  • 5. Example Single Instance Global Access Use it anywhere
  • 6. View 1 View 2 Users Store Some object Example - Diagram
  • 7. Example - Even more! View 1 View 2 View 3 Users Store Departments Store Singletons (DB / Backend) Connection
  • 9. Techniques 2 Synchronized lazy initialization Clearer, but lower concurrency Higher concurrency Ref: [2]
  • 10. Techniques - 3 Eager initialization No need for synchronization Ref: [2]
  • 11. Benefits ● State shared globally as required ● Global access; No complications to object access ● The object handles its own creation logic ● Hide details of the Singleton ● Can be used to implement some other patterns as well ○ Abstract Factory, Builder, Prototype …
  • 13. Singleton as an anti-pattern Singleton is popular because: ● It was included in GoF Design Patterns ● It’s easy; the easiest in the book People started a rebellion: ● Any design pattern can be abused, except for Singleton ● Valid motive, but ruins everything with its two steps Ref: [3, 10]
  • 14. Glorified Global Variables Have a bug? Now go over all those files for a clue! Mutable state 1 This one caused the bug 2 This one found it Ref: [4]
  • 15. Glorified Global Variables When some code uses a global variable, it’s harder to reason about it Mutable state 1 To know what this object / function is doing 2 You also need to understand what this is doing Ref: [4]
  • 16. Lifecycle The Singleton controls its own creation and lifecycle ● Violation of SRP: ○ Connecting to database is a responsibility ○ Creating, opening and closing the connection are other responsibilities ● Resetting the state is harder and more error-prone than creating a new object Ref: [3, 5]
  • 17. Lifecycle ● Now you have to make all Singletons reset to initial state ● You have to wait to reset properly ○ Sync data ○ Clear cache
  • 18. Lifecycle ● The user’s signed-in session is shorter than the application’s lifecycle. ● A global state, if necessary, should only handle states that last for the entire application’s complete lifecycle Ref: [5]
  • 19. Hiding Dependencies ● You don’t know what that Singleton needs ○ Singleton.getInstance() doesn’t explain much Data List Singleton What you see Data List Singleton What it actually is Connection Authenticator User Ref: [3]
  • 20. Hiding Dependencies - Example ● Only works when you run as part of the suite. ● When run in isolation, throws NullPointerException. Ref: [3]
  • 21. Hiding Dependencies - Example ● You ask a senior, and he tells you that CreditCardProcessor needs to be handled first ● Still, it throws an exception Ref: [3]
  • 22. Hiding Dependencies - Example ● You ask more. Now you know that both Database and OfflineQueue need to be initialized first ● The code worked! ● Now your bank account only has $12.5 because this code charged you for $100 Must be done in the same order! Ref: [3]
  • 23. ● The code is not stable, if Database gets modified, other classes may fail ○ Because you don’t know what depends on Database and how ● The code is not flexible, anything that depends on a Singleton is hard wired to that Singleton ● You can’t unit test a class without the Singleton initialized ● You can’t use mock objects for testing Hiding Dependencies Ref: [3]
  • 24. Encourage Coupling ● Since it’s global, any class anywhere can get it easily ● If the developer is thinking hard how to get it in that class, he would think if that class should get it Coupling between SomeTransaction and MySQLConnection Ref: [4]
  • 25. Encourage Coupling ● Now, you need to use a NoSQL database along with the SQL one ● SomeTransaction should switch to NoSQL database SomeTransaction MongoDBConnection MySQLConnectionTightly coupled Remove the coupling between SomeTransaction and MySQLConnection first
  • 26. Limiting Instantiation Are you really sure you won’t need another object of that Singleton class? nobacks.com SingletonScreen We only need one object for that one screen nobacks.com So what happens when I plug that screen to the laptop?
  • 27. Big deal! I don’t care if they’re bad or not. I only use one or two Singletons, what’s going to happen anyway? Source
  • 28. That’s the real problem! This one or two Singletons are strangling all or most of classes ○ Many classes are tightly coupled to it ○ Many classes can’t be tested properly ○ Change something in that Singleton and all other classes need to be changed as well
  • 29. The Root of the Problem This part is very legitimate! This is not Ref: [9]
  • 30. Solution ● Pass it a.k.a “Inject it!” ● Get it from somewhere already global ○ That place is responsible for creating it and managing its lifecycle ○ There are some evils that we can only reduce, but can never eliminate, like global state Ref: [7]
  • 31. Example A whole bunch of singletons Ref: [7]
  • 33. Example ● We’re sure that only one object is being used ● Dependencies are declared ● Dependencies are passed ● Each class is testable and mockable ● “Creation” is the factory’s responsibility ● If you ever need to have a new database, you don’t have to modify available classes Ref: [7]
  • 34. Immutable State Singletons Immutable state Singletons, enums in Java, objects in Scala, … are okay But still, be aware of coupling, limiting classes from inheritance, hiding dependencies … Ref: [9]
  • 35. References 1. c2.com: Singleton 2. Wikipedia 3. SO: What's so bad about singletons 4. gameprogrammingpatterns.com 5. Avoiding Singleton Abuse 6. programmers.stackexchange: So singletons are bad then what 7. Singletons are pathological liars 8. Where have all the singletons gone 9. Root cause of singletons 10. Singletons considered stupid