What's so bad about the Singleton?

I keep running into people who caution against using Singleton and recommend to avoid it like a plague. What is so scary about it?
— Kailash Badu

It’s a good question, for it is true that global variables are often demonised and more recently the Singleton has befallen the same fate. Perhaps a bit surprising, it is remarkably hard to find good arguments to support this common knowledge — Googling turns up a lot of confusion.

As I have often taken this stance myself, I found it reasonable that I should be able to argue for it, so I’ll try to give an explanation. This is also in part a follow-up on my post from last week, in which I present a way to avoid global symbols, without spending much time on why.

The anatomy of the Singleton

Some of the confusion around Singletons, comes from the fact that it is a manifestation of two different concepts, which each have a negative effect on an applications architecture. This muddies the case, since people tend to only deal with either one or the other of these two.

The most obvious of these concepts, is that the Singleton is a form of global state. It has this in common with global variables, as well as a couple of other — less obvious — manifestations hereof.

The other concept, that the Singleton contains, is that of static binding. Both of these are closely related to scope, which again has to do with drawing clear boundaries between sub-parts of a program.

But I’m getting ahead of myself.

Program state

Perhaps the simplest way to understand a program, is in terms of data and code. These two exists in separate worlds, with different rules associated. As the code executes, it manipulates the data, producing some kind of result. The data in a program, is known as state.

Since the basic unit of a program, is a function, state usually refers to the data, which relates to a function. A function is said to be stateful, if it changes it’s context, when run or if the context has any effect on the outcome of the function. Some times the term side-effects is used to describe the same thing. A function is said to be pure, if it always produces the same output, given the same input. For example, the following is a pure function:

 function add($a, $b) {   return $a + $b; } 

In the same terminology, a function which isn’t pure, is called a procedure. This is where the term procedural programming comes from. The following is an example of a procedure:

 function add($a, $b) {   echo ($a + $b); } 

Different shades of state

Global variables are a specific type of program state, but it’s not the only one. The above example (2) has a side-effect, without using a global variable — It writes out to the standard output. Another common kind of state, is mutable objects. For example, an object, which has a setName() -method, that changes the objects name, has side-effects (But the side-effects have a smaller scope, than global variables do). Even a local variable is stateful, within that functions body. While these are all examples of state, they represent different degrees on the scale.

What’s the problem, again?

As you may have guessed from the terminology (pure => good, side-effects => bad), it is implied, that state is bad.

The consequences of side-effects are two-fold. On one hand, they cause complexity. The problem is, that the i/o isn’t explicit. There is no way to know, by looking at the interface alone, what happens when invoking a function. This may be a small scale problem, but it adds up as the program grows.

The other problem is that of coupling. Since state can be shared between different functions, it may introduce a dependency between these functions. For example, if classes A and B both access the global variable G, then it is impossible to change G for A, without also changing it for B. This kind of dependency is called coupling.

There are remedies for excessive state in programs: Global variables can be replaced with local ones. Local variables can be replaced with function-calls (replace temp with query). Objects, which are passed around could be made immutable– This is especially important for long-lived objects, which interact with many parties.

Static binding

A program has two different kinds of existence; The compile-time and the run-time. Interpreted languages alternate between these, while a compiled language has a stricter separation. In any case, the symbols of a program, which take on a meaning in the compile-time, can’t change it’s meaning in the run-time. Examples of such symbols are constants, literals, class names and static methods (And in PHP, floating functions). Runtime-symbols (variables), on the other hand, can change their meaning.

Even though static symbols can’t change, they can still influence the outcome of a function, so in a very general sense, they are a form of state. It is usually not as important to avoid the state of static symbols, but in some cases, they may cause the same problems, as run-time state does. For example, static method calls cause static (compile-time) coupling. The Singleton is a prime example of this kind of coupling; If class A uses singleton S, then there is a strong coupling between A and S.

coupling

Coupling is of course unavoidable and to some extend even desirable. However, just like with run-time state, limiting it is a good idea. The problem with static coupling, is that it makes it hard (or even impossible) to reuse a component in isolation from other components, which it is coupled to. This is usually not an immediate problem, but it can have impact on maintenance. It also makes it hard to unit-test and debug code, because it isn’t possible to isolate a part of your program.

That’s all

I only just scratched the surface of the topic, but I hope this offers some explanation of why globals are frowned such upon. I’ll just leave you with the following quote:

Forgive Me Father, for I Have Singleton’ed
Kevlin Henney

Comments are — as always — welcome, but please refrain from biting off heads (Mine or others).

Replay

Category: programming Time: 2008-02-13 Views: 0
Tags:

Related post

  • What's so bad about the DOM? 2012-05-06

    I keep hearing people (Crockford in particular) saying the DOM is a terrible API, but not really justifying this statement. Apart from cross-browser inconsistencies, what are some reasons why the DOM is considered to be so bad? --------------Solution

  • What do you think about the Joel Test? 2010-09-11

    The Joel Test is a well known test for determining how good your team is. What do you think about the points? Do you disagree with any of them? Is there anything that you would add? --------------Solutions------------- Jeff Atwood has The Programmer'

  • What can we say about the stability of the network with this information? 2015-06-26

    While testing network stability with ping, requests timed out before MAX-TIME-TO-WAIT for each reply. I noted the lines that timed out before 500ms. COMMAND>ping google.com -n 20 -w 500 Pinging google.com [<google-ip>] with 32 bytes of data: Repl

  • Are questions about the Singleton pattern a good way to evaluate a job applicant? 2011-08-31

    I have been recently assigned the task of taking interviews in my company. I have been taking interviews of developers and engineers with atleast 5-6 years of experience. One of my favorite question is to ask whether they have used any kind of patter

  • What's So Bad About CSS Frameworks? 2009-02-17

    CSS frameworks are by no means breaking news. There have been several to choose from for a good couple of years now, with one of the earliest and most well-known being Yahoo's Grids CSS; we've talked about this previously in our blogs. What's amazing

  • What's so bad about creative coding? 2010-12-05

    I was watching Bob Ross paint some "happy trees" tonight, and I've figured out what's been stressing me out about my code lately. The community of folks here and on Stack Overflow seem to reject any whiff of imperfection. My goal is to write res

  • What can you do about the quality of existing integration and unit tests while being the new guy in a team ? 2011-09-08

    A recurring theme that I came across in my career is being the new developer to arrive in a team, and quickly having an inherent distrust of the existing unit and integration test suites. During the interview you are told by the management that they

  • What's so bad about pointers in C++? 2012-09-02

    To continue the discussion in Why are pointers not recommended when coding with C++ Suppose you have a class that encapsulates objects which need some initialisation to be valid - like a network socket. // Blah manages some data and transmits it over

  • What has research shown about the effectiveness of comments? 2012-02-23

    I have been arguing with a friend about the necessity of comments, and the efficiency of different comment styles. The argument ended quite fast, as we could not find any research - or essay - that support either claim. Has any serious research been

  • What can be done about the calendar app closing itself on an iPad? 2012-08-30

    I have been using my calendar fine but this afternoon when I click on the tile it briefly opens (1 sec) and then closes itself. I have waited 30 mins, I have turned iPad off & back on and still no joy. --------------Solutions------------- This is how

  • Permutation algorithm: What is so bad about this code? 2013-12-06

    I was asked to write a permutation algorithm to find the permutations of {a,b,c}. Since this is a famous question to which an answer is readily available online, I wanted to do it a little differently, so that it wont look like I copied off the inter

  • What do you think about the Extension Object Pattern within rich domain models? 2016-07-25

    Let's assume an employee, wich has several tasks to do: post time for time-tracking purposes request a day-off or vacation ... you could implement every task into a service or another rich domain model (e.g. time-tracking model or vacation model), bu

  • What do you think about the results of 3M Visual Attention Service's Web App? 2011-01-27

    First of all if you haven't heard of this service here's the link: https://vas.3m.com/ This online app generates heatmaps: you get 5 credits free at first, with which you can analyze the pictures of I would like to ask that if you have tried this app

  • What can I do about the 2 SATA harddrives no longer showing up even in BIOS? 2011-08-04

    I've been trying to setup Ubuntu but have been running into countless issues. Both the 500GB drives has now become undetectable and don't even show up in BIOS. I've detailed below the process I've gone through in case it lends anyone a clue. At the s

  • As an indie developer, what should I learn about the business end of game development? 2012-02-23

    I assume I should look into intellectual property law, copyright law, and money management, but what else would be good to know? My ideal goal is to be able to handle all legal/monetary business internally, without hiring an outside lawyer. ---------

  • What can be done about the long URLs? 2011-08-11

    I'm used to using wikis with short, predictable URLs: host+page name. Suddenly with SharePoint 2010 I'm confronted with long, apparently unpredictable paths to files. I was triggered on this today when I wanted to email a colleague a link to a file o

  • What can I do about the fglrx driver interfering with jackd? 2012-05-13

    The jack-audio-connection-kit needs to run in realtime mode and my system is configured accordingly. I'm using the fglxr driver. With Unity-2d everything is fine. With Unity-3d, jack-clients disconnect from jack very often, usually when something hap

  • What do I do about the "haziness when booting up Ubuntu?" 2013-05-12

    I have installed Ubuntu 12.04 LTS, the Windows Installer method, and when I restarted and booted up Ubuntu, it was static and hazy. I rebooted back to Windows 7. I did like Ubuntu for about two minutes, but that haziness was just too much, and I coul

  • What's so bad about xtemplate collections? 2014-01-27

    The xtemplate documentation describes (briefly and a little unhelpfully) the concept of 'collections' in xtemplate. It goes on to say, However, while the idea of switchable instances is a useful one, the team feel[s] that collections are not the corr

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 1.806 (s). 13 q(s)