3 ms·
> Mutable instance variables are much less bad because their scope is much more limited: you can much more easily scan all the code that mutates them and check
by __sr__ 8y ago
> Mutable instance variables are much less bad because their scope is much more limited: you can much more easily scan all the code that mutates them and check that invariants are upheld etc.
Same can be done with module level globals.
- mpartel 8y agoYou're right, assuming the module is not too large. There's another point in favor of instance variables: it gives you the flexibility of multiple values in different parts of your code. As codebases grow, the danger of two unrelated places wanting different values for your global also grows. Say a physics simulation has a global for gravity. This precludes, or at least unnecessarily complicates, the same process from having two separate simulations with different gravities (perhaps in different threads). This is especially bad in library code.
- __sr__ 8y agoAgreed, and module globals shouldn’t be used for such cases. But for simpler cases, it may, in some cases, be better to use globals than create a singleton or some other convoluted solution. To be clear, I am not saying globals should be used everywhere. There are a programming construct just like any other. When used carefully, they can greatly simplify code — but also have the potential to horribly complicate the code when abused. And that is true about any programming construct. One thing that irritates me is the tendency to paint things black and white — eg. goto, globals, multiple inheritance etc. are bad. So “modern” programming languages try to eliminate them in a misguided attempt to keep programmers safe from themselves. I agree that these things are often misused, but a bad programmer will figure out a way to misuse anything — or do you think it is impossible to write bad code in something like, say, Go? Dumbing things down doesn’t prevent bad programmers from messing up, instead it causes the rest to write horrible code because of the lost power.