GoogleTechTalks – The Clean Code Talks (2)

The Clean Code Talks – “Global State and Singletons”

One more great presentation. This one is more focused on dependency injection, which advocates a way to clearly declare their dependency through constructors instead of using global singleton objects.

It would also be a good presentation for understanding the benefits of AngularJS. As also talked in the Q&A (around 45:30), JavaScript involves global states through DOM manipulations. With AngularJS, it is separated into HTML tags by the framework, and controllers just have to accumulate object data for the HTML views. Also, controllers can declare the dependency to the services/factories in the method arguments, and also the framework just automatically resolves the dependency.

Dynamic languages like JavaScript or Ruby may not have huge issues mocking the global-state objects for tests, compared with Java. But, it would simplify the testing code. Also, this pattern exposes the inappropriate dependencies between objects, and would be good for designing modular components. Even without checking call graphs, developer can know the possible design flows during development.


Singleton method enforces to have one instance for entire JVM (in Java case), rather than having one instance for an application. It makes difficult to run tests or run multiple applications simultaneously. Testing is a kind of executing small part of the application repeatedly without throwing up the environment entirely each time (It’s due to performance reasons).

If the singleton is abused, it becomes difficult to control its dependency as follows. CreditCard depends on Database, OfflineQueue, CreditCardProcessor, but the relationships are not obvious.


testCharge() {
  CreditCard cc = new CreditCard("12..34");

One solution is to change the singleton into normal objects and pass them in the constructor of the application which uses them. It makes it easier to control the status of the objects and also easier to mock them during tests.


testCharge() {
  db = new Database(...);
  queue = new OfflineQueue(db);
  ccProc = new CreditCardProcessor.init(queue);
  CreditCard cc = new CreditCard("12..34", ccProc);

Posted on June 9, 2013, in Software Design, Web. Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: