4 ms·
A singleton restriction is a guide to other programmers in the team as to how to use your class. i.e., "don't create multiple instances of my Cache class, use t
by petilon 5y ago
A singleton restriction is a guide to other programmers in the team as to how to use your class. i.e., "don't create multiple instances of my Cache class, use this one instance, otherwise you defeat its purpose". It is a good idea.
- moron4hire 5y agoYou might think today, "I only need one cache", but that assumption might not hold in the future. The problem with Singletons is that you are deciding for everyone who is ever using your code that there will be only one instance of that class. The original article is right. That's not the concern of the class you're writing. That's a concern of the context that is using the class. Dependency injection is better for this sort of issue.
- jackblemming 5y agoThen they can refactor it to not be a singleton in the future. It definitely could be a concern of the class. What if having multiple copies caused catastrophic consequences?
- petilon 5y agoConstraints such as singleton give guidance on how to use your code. If you remove constraints then it is harder to figure out intended usage. Sure constraints may need to be modified in the future, but that doesn't make constraints useless. A simple example of a constraint is 'private' modifier on a method. You could make your arguments against 'private' constraint and say "that's an assumption that might not hold in the future", so we shouldn't have private methods.
- moron4hire 5y agoExcept these two things--single instance-ness of classes and private-ness of class fields--are not comparable things. There's no way to easily change a field from public to private without breaking an unbounded set of code. The Singleton pattern is similarly difficult to change the lifetime of an object without breaking code. But we can achieve the same, desired results of Singleton with Dependency Injection, which can change the lifetime of an object without breaking dependent code. We have no such alternative for field access modifiers. Yes, these things are tools, and in some cases, better tools have been invented.