4 ms·
You may as well just use a singleton pattern if you're going to do this, and at least that's easier to maintain if your use cases change.
by Vanit 2y ago
You may as well just use a singleton pattern if you're going to do this, and at least that's easier to maintain if your use cases change.
- pinoy420 2y agoNot sure how that is any different besides construction of an object rather than a file with globals?
- jwarden 2y agoA singleton object can encapsulate the global state, converting global variables to private fields. How would this be different? Because a counter singleton can for example disallow directly setting the count field, only allowing the count to be incremented through a method.
- int_19h 2y agoYou don't need objects for that kind of encapsulation, just don't export your variables across module / unit boundaries.
- jwarden 2y agoYes good point. The module/unit acts as the singleton instance, in a sense, though that might be the incorrect way to put it. In any case, I think variables that are “global” but encapsulated in this way lose the potential for harm we associate with a global variable the whole program may be directly reading and writing.
- n0w 2y agoI think the suggestion is to encapsulate global mutable state behind a strict interface (if you want global mutable state)
- chikere232 2y agoSingletons are just globals for people who have learnt "globals are bad" but lack a deeper understanding
- Salgat 2y agoNot exactly. For example, you can have a singleton object that maintains a persistent connection to a db to persist logs to. No one's going to inject the "ElasticsearchLogger" object in their method/class by accident, and even then, they'll only have access to the singleton state that the class lets them have access to. So now your private Counter variable is inside a global singleton without being accessible by anyone, even if that person is disregarding all of OP's rules.
- flohofwoe 2y agoJust use a flat C-style function API instead of a Singleton object. Singletons are only really needed in languages that enforce the 'everything is an object' folly.
- levodelellis 2y agoI'm the author No, please don't