[rspec-users] class << self considered harmful... really?

Zach Dennis zach.dennis at gmail.com
Tue Nov 25 09:38:36 EST 2008

On Tue, Nov 25, 2008 at 8:41 AM, Matt Wynne <matt at mattwynne.net> wrote:
> Sorry, I know this is off-topic, but I'd really like to know what the
> revered ruby-hackers who read this list think.
> See
> http://ozmm.org/posts/class__self_is_harmful.html
> I have adopted class << self, partly from reading RSpec and Cucumber's code
> as I learn Ruby. I personally think of class methods (or 'static' methods)
> as being in a kind of 'holding pen' waiting to be factored off onto a proper
> class of their own, so I rather like the clear way you can group them in a
> 'nameless' metaclass ready for the exit door.
> I also really like the clarity of seeing the invisible metaclass for what it
> is.
> What do people think? How can this be harmful?

I think the issue is that people are using class << self to access the
virtual class when they don't need it. I've seen code where you have
to scroll to see all of the methods implemented inside of class <<
self. Adding methods to a virtual class does make method dispatching
in ruby less efficient, but I don't think enough to render it

The virtual class of an object (class or instance alike) gives you the
ability to modify the object in ways that a simple class method
usually does not allow. For example, if you want to break down a class
method into a couple of methods, but you don't want to support all of
the methods as a public API. Here you can use class << self to
privately scope some of those helper methods that you just decomposed.

My rule of thumb is to use it when I can't easily achieve the same
result using other mechanisms, but not to use it just cause'.

Zach Dennis

More information about the rspec-users mailing list