1

My question is simple: should I create my Debug class as a singleton?

I know that the singleton pattern is a bad practice, but a debug class does not take part in the logic in an app, and it would complexify the entire application to inject the debug class into every class.

My debug class would contain methods such as:

Debug::message();
Debug::dump();
Debug::spot(); // To create a timeline
// etc

It should also be noted that I use the debugbar package, and that it will only be present in dev mode, so my debug class will look if the package is present, if so, it will pass the informations to it, otherwise, it will just do nothing (or maybe log important things).

tleb
  • 4,395
  • 3
  • 25
  • 33

1 Answers1

1

Ok, so you want to do do static calls to avoid tossing around an instance of your debug class. Makes sense.

And if you want to use static calls, then the alternative to a singleton would be to write a class that consists only of static properties/methods.

The decision whether you go for that or for a singleton is pretty simple: Does this class have an internal state and/or require a constructor? For example, if you open a log file or instantiate other objects, you’ll definitely want a singleton.

Singleton is frowned upon, and there are good reasons for this. But there are still situations where it makes sense and is a valid approach.

You mention that you want to create a timeline, so I guess that you need to initialize the timestamp. You have a dump method, so I guess that you want to collect certain information to dump it later. These things are usually stateful.

Of course, you could call some sort of Debug::init() at the top of every public method, but that would be stupid and worse than a singleton.

So, in your specific case, I guess a singleton would indeed make sense.

Community
  • 1
  • 1
lxg
  • 12,375
  • 12
  • 51
  • 73
  • Thank you. This convinced me that using static calls can be accepted in some cases. I think I will go with a singleton, so that I can pass my instance of the debugbar at the beginning of the script. – tleb Jul 05 '15 at 20:44