In general which is better for a global cache: global variable, constant, or class instance variable?
Here is an example of each:
module Foo
$FOO_CACHE = {}
def self.access_to_cache
$FOO_CACHE
end
end
module Foo
CACHE = {}
def self.access_to_cache
CACHE
end
end
module Foo
@cache = {}
def self.access_to_cache
@cache
end
end
This is ultimately pretty subjective, but I’ll address each option one-by-one:
Global variable: no …because putting a global variable inside a module (or a class, or anything for that matter) doesn’t make much sense, it’s going to be in scope everywhere anyway. Besides the fact that if you can use something other than a global variable, you should always do so.
Constant: no …because the cache is not constant! While Ruby doesn't enforce that constants can’t change, that doesn’t mean you should do it. There’s a reason they’re called constants.
Class instance variable: yes …because it’s the only one here that makes any sense (though the name might not, technically here it’s a module instance variable, but that’s being rather pedantic). This is the only one of the three that both makes semantic sense to modify and is encapsulated by some scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With