Object-oriented – n’t a static class have an internal state

object-orientedsingletonstatic-access

While working on a project, I decided to create a database class to manage my DB connection. I started looking for the best practice to do that, which is usually either a static class or a singleton pattern class.
Answers I've found, such as:

http://javarevisited.blogspot.com/2013/03/difference-between-singleton-pattern-vs-static-class-java.html

When to use a Singleton and when to use a static class

Favor the singleton approach over the static one, for mostly understandable reasons (easier to make thread-safe, easier to make use of OOP features, easier to test…), but one reason I can't understand is that static classes shouldn't have any kind of state. Could someone explain the reason behind that?

Best Answer

Why shouldn't a static class have an internal state?

Because, in the context you're linking to, not having internal state is the DEFINITION of a static class.

Here static class doesn't mean static class. It means java.lang.Math. That's a final class full of static methods.

Now that our vocabulary is clear...

@Doval Why shouldn't it? – Aviv Cohn Apr 10 '14 at 14:02

Well...

@Prog Because you're just using global variables in disguise. All parts of your application that make any calls to the static class are now invisibly dependent on each other, and any parts of your application that are dependent on those parts are now indirectly dependent as well, and so on. Mutable state is already a bad idea if you can avoid it. Global mutable state is just a bad idea. – Doval Apr 10 '14 at 14:05

So why

Favor the singleton approach over the static one

Because Murphy was an optimist. You say you only have one DB resource now but suppose that changes?

Designing around the idea that there will only ever be one of anything is forgetting why we solve some problems with keyboards, not soldering irons.

I favor the immutable instance approach (I can't bring myself to say singleton because the GoF singleton pattern is so so so not optimal) because shared mutable state is the real sin.

Give me a way to get an immutable instance that points to the DB resource you want me to talk to and I'll talk to it. Whether it talks to your 1st or 2nd DB resource is none of my business.

That's dependency injection. Counting the number of of DB resources is now a problem pushed out into construction. From there you could push it out to configuration if you wish.

Now I'll admit I'm biased. You don't have to use DI. You can use singleton. Here's a well considered article a comparing Singleton vs Dependency Injection.

I'll jump to the summery:

  1. If a dependency is ambient, meaning that it is used by many classes and/or multiple layers, use Singleton.
  2. Otherwise, inject it to the dependent classes using the Dependency Injection pattern.

Which I love because it lets me simply say this: don't write code that puts your DB in case 1.

Related Topic