There are times when globals make sense. A lot of people talk about the dangers of global variables and I agree that they should be used sparingly. It's a discussion that's been had over and over again. But let's see if we can decide a rule for when we are willing to allow ourselves to use a global.
So what is a "global"?
A global is a shared resource that can be accessed at any time, from anywhere. Since this type of access breaks many conventional notions of good software engineering, they are usually dismissed as bad. The mere existence of a global indicates an elevated sense of importance. In a way, the only way to express this criticality is in the form of a global.
Globals must align with the essence of the software. Such that when removed or rendered impossible, you would abandon the project, or it would become a different project entirely.
Let's talk about ruby. There are a few standard integrations that are essential to the functionality of the software and they are elevated to the status of global. If you use the fantastic Sequel gem, the README literally recommends you assign the connection to the database as a global. This communicates that database interop is so essential to what you're working on that there's no point in abstracting it away behind any other layers. If somehow it became forever impossible to access the database, there's a reasonable chance you would abandon or pivot the entire project. When you have a concept THAT important, you are allowed to make it global. If you use Rails, there is already built-in support
Integrations can be a special case
There's a lot of code that exists simply to integrate into other services. If you are making a salesforce app integration, your salesforce client can be global. Why? You can build your plugin with standard techniques, but by its very nature, it will always depend on Salesforce or be obsolete. If you accept that as part of the essence of what you're working on, you can sidestep a ton of extra architecture and design and just be productive.
I haven't seen any other justifiable uses of globals, and I still tend to steer clear of them, however, I hope this gives you a different perspective on the subject.
If you like these ideas and would like to work with me, drop me an email at contact@gofrias.com
Top comments (0)