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

Mark Wilden mark at mwilden.com
Thu Nov 27 18:43:34 EST 2008

On Thu, Nov 27, 2008 at 1:59 PM, Brian Takita <brian.takita at gmail.com>wrote:

> Its funny because I consider def self.foo harmful for a few reasons.
> def self.method_name is often mixed with instance methods. This makes
> reading the code confusing because there are two contexts that you
> need to deal with.

Solution: Don't do that.

> Also, like you mentioned, using def self. obfuscates an object
> extraction that needs to happen. With class << self, I can think about
> refactoring an object, rather than refactoring class methods. class <<
> self allows me to think of class/modules in a more object oriented
> way.

In general, in OOP, I've found class methods to be far less numerous than
instance methods. Class methods by their very nature are not OOP - they're
not much different than global functions. In Ruby, this is not as true, of
course, and class methods are just instance methods of a different kind of
object. When you're using them as such, opening up that object with class <<
self is a good idea. If you're not, then you shouldn't have very many of
them and wouldn't need to refactor them out.

> I also like how all of the class << self methods are organized into a
> single section. Yes, its difficult to read if it takes more than a
> screenful, but I prefer it to having to track down all of the def
> self.method_name methods spread all over the place.

This is just a question of coding style. You can gather all your def
self.foos in one place, and you can have multiple class << self sections
(the latter being bad and the former good)

> Also, class << self is more powerful. It allows you to use one way to
> use your convenience methods (attr_*, include) and parser instructions
> (public, private, protected). Nothing is worse than having to use both
> def self.method_name and class << self.

I agree with that. But I also believe in doing the simplest thing that could
work, and using two extra lines of code when it's not necessary fails that
test. If it is necessary, that's a different matter, of course.

When I get back into work on Tuesday, I'll dig up what Matz says in RPL
(unless someone else has a copy?)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://rubyforge.org/pipermail/rspec-users/attachments/20081127/e93179bc/attachment.html>

More information about the rspec-users mailing list