Globals or objects?
steve at holdenweb.com
Thu Feb 21 13:40:40 CET 2008
MartinRinehart at gmail.com wrote:
> I had a global variable holding a count. One source Google found
> suggested that I wouldn't need the global if I used an object. So I
> created a Singleton class that now holds the former global as an
> instance attribute. Bye, bye, global.
> But later I thought about it. I cannot see a single advantage to the
> object approach. Am I missing something? Or was the original global a
> better, cleaner solution to the "I need a value I can read/write from
> several places" problem?
Look up "coupling" and "cohesion" in Wikipedia or similar, and you will
find out that global variables are bad because they introduce tight
coupling between different pieces of functionality in your code.
If a function uses a global variable then you have to initialize the
same global variable in another program that uses it: yet another piece
of setup you will forget to do.
Having said that, where are you storing the reference to the singleton
instance? It wouldn't be a global, would it?
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list