11 ms·
If there is a good use for it... Why not? In medicine stuff that normally hurt you is used to cure you as well... You just need to know when and how to use it.
by pmelendez 14y ago
If there is a good use for it... Why not? In medicine stuff that normally hurt you is used to cure you as well... You just need to know when and how to use it.
- malkia 14y agoThere is no good use for singletons. void callback_from_read(int err) { #if USE_SINGLETON if( err < 0 ) log::instance()::printf("blah... err=%d", err); #else if( err < 0 ) theLog->printf("blah... err=%d", err); #endif } ... do_read( something, somesize, callback_from_read ); ... Now thing about it. If this read came from the I/O in some thread with limited stack, it would've wanted to initialize theLog::instance():: the first time it calls it. That function itself might want to read a file, but the underlying system does not allow a file to be reopened while it's still in the I/O callback. Even if it does, there might not be enough place on the stack, or it could be called from a thread where the stuff you are trying to do is not going to work. Ah, and you would have to make it thread safe at this point (if the callback is in a thread), since someone might've called log::instance()::printf() from the main-thread. Other things might happen if more locks are involved, and different thread priorities like priority inversion. The problem is that log::instance()::printf() might do two things - INIT_LOG(), and DO_LOG() - the singleton pattern combines them into ONE, where it should've kept them separate. You might be able to reason about DO_LOG anywhere in the code, but combined with INIT_LOG becomes very hard, and even impossible. As such singletons are introducing coupling, and reduce severely the reasoning about what the code might do.
- pmelendez 14y agoI thought I was very specific... "There are good uses for singleton classes in single threaded applications that don't use unit tests " In any case I didn't say that logging was the only use. In gaming, we had used it a lot when sharing single resources across all the game such a config file. And if you can take a peak to Unreal Engine you would see how those guys abuse of them without too many problem. I do not want to be an advocate of using Singletons. I am aware of the risks and problems it brings with. But sometimes people forget that not every application is multithreaded nor implement unit tests. My fear with that is when people forget why it was bad on first place (just like it happened with the goto keyword).