Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why aren't global (dollar-sign $) variables used?

I'm hacking around Rails for a year and half now, and I quite enjoy it! :)

In rails, we make a lots of use of local variables, instance variables (like @user_name) and constants defined in initializers (like FILES_UPLOAD_PATH). But why doesn't anyone use global "dollarized" variables ($) like $dynamic_cluster_name?

Is it because of a design flaw? Is it performance related? A security weakness?

like image 582
Hartator Avatar asked May 08 '11 12:05

Hartator


1 Answers

Is it because of design flaw issue ?

Design... flaw? That's a design blessing, design boon, design merit, everything but flaw! Global variables are bad, and they are especially bad in Web applications.

The sense of using global variables is keeping—and changing—the "global state". It works well in a simple single-threaded scripts (no, not well, it works awful, but, still, works), but in web apps it just does not. Most web applications run concurrent backends: i.e. several server instances that respond to requests through a common proxy and load balancer. If you change a global variable, it gets modified only in one of the server instances. Essentially, a dollar-sign variable is not global anymore when you're writing a web app with rails.

Global constant, however, still work, because they are constants, they do not change, and having several instances of them in different servers is OK, because they will always be equal there.

To store a mutable global state, you have to employ more sophisticated tools, such as databases (SQL and noSQL; ActiveRecord is a very nice way to access the DB, use it!), cache backends (memcached), even plain files (in rare cases they're useful)! But global variables simply don't work.

like image 165
P Shved Avatar answered Oct 13 '22 20:10

P Shved