Global variable vs. constant vs. class for global cache

In general, what is better for a global cache: a global, constant, or instance class variable?

Here is an example of each of them:

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 
+4
source share
1 answer

This is ultimately quite subjective, but I address one of them each option:

  • Global variable : no ... because putting a global variable inside a module (or class or something like that) doesn’t make much sense, it will be in any case in the whole area, Besides the fact that if you can use something, different from the global variable, you should always do this.

  • Constant : no ... because the cache is not permanent! Although Ruby does not apply constant changes, this does not mean that you should. This is the reason they are called constants.

  • Class instance variable : yes ... because its only one makes sense here (although the name may not be there, technically it is a module instance variable, but it is rather pedantic), This is the only one of the three that makes semantic meaning a modification and is encapsulated by some area .

+5
source

Source: https://habr.com/ru/post/1414663/


All Articles