2 ms·
Classes exist to bundle state; if there's no need for state, there often shouldn't be a class in the first place. I tend to use module_fun for that, or just:
by aphyr 14y ago
Classes exist to bundle state; if there's no need for state, there often shouldn't be a class in the first place. I tend to use module_fun for that, or just:
module Foo
def self.some_stateless_method
...
end
end
Foo.some_stateless_method
class MyController
include Foo
def index
some_stateless_method
end
end
and so forth.
People think of modules as being mixins, but they're actually just function namespaces--which you can happen to bind into class contexts via include/extend.
I tend to use class methods where:
a.) The class exists, because you want state, and
b.) The function operates principally on, or is only useful in, the context of that class, but
c.) The function isn't bound to the object's state.
That last requirement is fuzzy, since the call semantics are different: self.class.foo is awkward, so I'll often write instance methods which don't actually depend on the state, just taking advantage of the local namespace.