News for hackers. Stuff that matters.
Re:Am I Doing it Wrong? by aphyr on Friday June 22, 2012 @06:02PM (#4149065)
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.

There are no comments on this comment yet.