DEV Community

Discussion on: Are global variables bad?

Collapse
 
strredwolf profile image
STrRedWolf

The question still requires more information, because it depends on the situation it is in.

Take embedded programming with an "easy" case: a small photo display used for showing electronic convention badges at fan conventions. Yes, I built two versions.

Here, you have a situation where your program is the only thing running. There's no OS because there's no room for it -- you are the firmware and the OS. You got 30K of ROM and maybe 2K of RAM at the minimum. Oh, and you have to track which photo you opened, and some of that RAM can be used as a buffer for the pixels you're reading.

Arduino is embedded programming.

So, yes, global variables are good if used sparingly in this situation.

Now take something two levels up: You're using a Raspberry Pi that's on the International Space Shuttle. You're displaying sensor data and if things get into a warning level, you're flashing a warning. You're an application on the Rasbian OS. You got almost half a gig of RAM.

Here, the need for global variable across your code is... well... next to nil. Plus, most libraries can't access your global variables unless explicitly asked for. The only global you probably will have is the glibc standard "errno" which everything uses. If you're using a language that's not C, all of that is abstracted away into Exceptions, and you can trap those (try/catch/throw).

In this case, global variables have to have a damn good use case for them. Otherwise, they're in lower scope levels, and get more insulated from each other -- they don't become global. They start becoming localized.

I haven't come across a C# program that had global variables (probably because the program itself was wrapped in a class). But I've come across many Arduino sketches that needed them.

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

Yes, context is important. It's what I was hinting at when I mentioned a micro-service architecture, but didn't want to get into too many other options.

I also mentioned briefly that the "type" of the variable is important as well. This can also depend on domain, and threading, but certain types, like fundamentals, are a bit safer as globals than large classes, or pointers.