开发者

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

开发者 https://www.devze.com 2023-03-03 13:44 出处:网络
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 initializ

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 FI开发者_如何转开发LES_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?


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.


Global variables are often a sign of bad design, and can be a source of bugs due to concurrency issues. Global constants don't really have these issues.

Instead of using a global variable, consider using a singleton or a class variable. That way, you can limit access to the shared state to a small part of your code, making it easier to avoid these problems.


I've once used them to keep FTP connections alive across AJAX calls for a web-based FTP client. This allowed the user to repeatedly interact with their FTP site without having to reconnect each time for every action performed.

So one nice benefit of globals in Ruby is that you can safely store resource type objects in them.


The apparent lack of global usage is an indicator of the flaw of global variable concept, not of ruby's implementation of them. In fact, I didn't even know ruby had a $global syntax. They aren't needed, and so I have never looked for them. Good ruby code never needs them.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号