Home > C++, programming > Why globals should be avoided

Why globals should be avoided

I thought avoiding globals was so widely accepted now that people just did it without thinking, then I came across a new one during a code review and marked it as a defect, assuming it was fairly self explanatory.  To my surprise, the author disagreed strongly, defending his code like it was his firstborn child.  The other option would mean putting it in a header file, and since so many other files included that header, he didn’t think that would be safe this close to release.

Well, yeah.  What part of “global” made you think a lot of code wouldn’t be affected?  And you thinking adding a global is safe, but a one line change to a header file is dangerous frankly scares me a little.  Okay, that’s what I wanted to say, but I was stymied because I’d accepted avoiding globals as a best practice for so long, I had forgotten why. Then I came across this reddit post and thought this was probably something we all could use a refresher on, so here goes.

  • Namespace pollution.  Inside our home, everyone knows “Michael” refers to my son.  Anywhere else, we have to be more specific.  Only use a global if you’re absolutely sure no one else in 500,000 lines of code will ever want to use the same name for a different purpose, like for system-wide exception handling or something.
  • Errors don’t get caught until linking.  If you’re using dynamic linking that could be a big problem, and even with static linking error messages aren’t as easy to track down as a compiler’s.
  • Bigger chance of a semantic mistake like thinking you’re using the same global in two places, when you’re actually using two with slightly different spellings.
  • Bigger chance of multi-threading issues with two threads accessing the same variable at the same time.
  • Harder to determine where that variable is defined and everywhere it is used.
  • Harder to change implementation details because a global could be used anywhere instead of just easily defined boundaries.

Anything I missed?  Ideas on circumstances where globals are acceptable?  Let me know in the comments.

About these ads
Categories: C++, programming
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: