the perks and perils of the singleton design pattern

36

Upload: badr

Post on 11-Apr-2017

38 views

Category:

Software


1 download

TRANSCRIPT

Page 1: The Perks and Perils of the Singleton Design Pattern
Page 2: The Perks and Perils of the Singleton Design Pattern

Singleton The Perks and Perils of the Singleton Design Pattern

Page 3: 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

Page 4: The Perks and Perils of the Singleton Design Pattern

Solution

Head up to that class, and:

● Restrict the class to create only one object

● Provide global access to it

Ref: [1]

Page 5: The Perks and Perils of the Singleton Design Pattern

Example Single Instance

Global AccessUse it anywhere

Page 6: The Perks and Perils of the Singleton Design Pattern

View 1

View 2

Users Store

Some object

Example - Diagram

Page 7: The Perks and Perils of the Singleton Design Pattern

Example - Even more!

View 1

View 2

View 3

Users Store

Departments Store

Singletons

(DB / Backend)

Connection

Page 8: The Perks and Perils of the Singleton Design Pattern

Techniques

Lazy initialization

Ref: [2]

Page 9: The Perks and Perils of the Singleton Design Pattern

Techniques 2

Synchronized lazy initialization

Clearer, but lower concurrencyHigher concurrency

Ref: [2]

Page 10: The Perks and Perils of the Singleton Design Pattern

Techniques - 3

Eager initialization

No need for synchronization

Ref: [2]

Page 11: The Perks and Perils of the Singleton Design Pattern

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 …

Page 12: The Perks and Perils of the Singleton Design Pattern

The endNot really!

Page 13: The Perks and Perils of the Singleton Design Pattern

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 stepsRef: [3, 10]

Page 14: The Perks and Perils of the Singleton Design Pattern

Glorified Global Variables

Have a bug? Now go over all those files for a clue!

Mutable state

1This one

caused the bug

2This one found it

Ref: [4]

Page 15: The Perks and Perils of the Singleton Design Pattern

Glorified Global Variables

When some code uses a global variable, it’s harder to reason about it

Mutable state

1To know what this object / function is

doing

2You also need to

understand what this is

doing

Ref: [4]

Page 16: The Perks and Perils of the Singleton Design Pattern

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]

Page 17: The Perks and Perils of the Singleton Design Pattern

Lifecycle

● Now you have to make all Singletons reset to initial state

● You have to wait to reset properly○ Sync data○ Clear cache

Page 18: The Perks and Perils of the Singleton Design Pattern

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]

Page 19: The Perks and Perils of the Singleton Design Pattern

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]

Page 20: The Perks and Perils of the Singleton Design Pattern

Hiding Dependencies - Example

● Only works when you run as part of the suite.

● When run in isolation, throws NullPointerException.

Ref: [3]

Page 21: The Perks and Perils of the Singleton Design Pattern

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]

Page 22: The Perks and Perils of the Singleton Design Pattern

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]

Page 23: The Perks and Perils of the Singleton Design Pattern

● 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]

Page 24: The Perks and Perils of the Singleton Design Pattern

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]

Page 25: The Perks and Perils of the Singleton Design Pattern

Encourage Coupling

● Now, you need to use a NoSQL database along with the SQL one

● SomeTransaction should switch to NoSQL database

SomeTransaction

MongoDBConnection

MySQLConnectionTightly coupledRemove the coupling between SomeTransaction and MySQLConnection first

Page 26: The Perks and Perils of the Singleton Design Pattern

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 plugthat screen to the laptop?

Page 28: The Perks and Perils of the Singleton Design Pattern

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

Page 29: The Perks and Perils of the Singleton Design Pattern

The Root of the Problem

This part is very

legitimate!

This is not

Ref: [9]

Page 30: The Perks and Perils of the Singleton Design Pattern

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]

Page 31: The Perks and Perils of the Singleton Design Pattern

Example

A whole bunch of singletons

Ref: [7]

Page 32: The Perks and Perils of the Singleton Design Pattern

Example

new OfflineQueue(database)

Ref: [7]

Page 33: The Perks and Perils of the Singleton Design Pattern

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 classesRef: [7]

Page 34: The Perks and Perils of the Singleton Design Pattern

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]

Page 35: The Perks and Perils of the Singleton Design Pattern

References1. c2.com: Singleton2. Wikipedia3. SO: What's so bad about singletons4. gameprogrammingpatterns.com5. Avoiding Singleton Abuse6. programmers.stackexchange: So singletons are bad then what7. Singletons are pathological liars8. Where have all the singletons gone9. Root cause of singletons

10. Singletons considered stupid

Page 36: The Perks and Perils of the Singleton Design Pattern

Questions?