Inversion Of Control: An Architect's Version of Global Variables
- Sunday, April 01, 2012
One of the tomes we live by: "Global Variables are EVIL!!!!!!" - so we abstract our stuff into patterns and build up highly ceremonial and ornate bits of dramaware called "IoC Containers". For what? To use Global Variables - That's Why.
You Love Globals
No really. You do. Let's just embrace that this very second. Tell me what this difference isbetween this code sample:
I'll tell you the difference: in one sample the coder admits they have a problem.
In the other they pretend the problem's not there by wrapping it in ceremony, abstraction, configuration files, and Gang of Four nonsense. Can you guess which one is which?
After all is said and done I think it's fairly clear: we're addicted to globalization.
Possibly you disagree with me. In fact I have a feeling that you
really disagree with me. And that's OK - it takes a while to admit it.
It took me forever to realize that I've been globalizing everything since my VB Days.
Look at this way: at least you're aware of it now.
Free The Global Love
One thing we've always been told: "Globals are bad". They're bad because
outside forces can change the state of a given global variable which would, in turn,
leave your application in a somewhat random, difficult to debug state.
Sounds horrible, no? If you think so, take a look at the first sample above. What
silliness do you see there? Me changing a global setting of course! Now I
understand completely that this is a bad idea - but think about it a bit more. I
changed the container setting by simply by using the Rebind() method on the
kernel - why is this even possible?
Every now and again I think it's really a good idea to look at the code we're writing
really carefully... and ask if what we're doing makes any sense at all.