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

Matt Wynne matt at mattwynne.net
Tue Nov 25 11:54:31 EST 2008


On 25 Nov 2008, at 16:48, Pat Maddox wrote:

> "Zach Dennis" <zach.dennis at gmail.com> writes:
>
>> On Tue, Nov 25, 2008 at 11:08 AM, Mark Wilden <mark at mwilden.com>  
>> wrote:
>>> On Tue, Nov 25, 2008 at 5: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.
>>>
>>> The nature of class methods in Ruby (as instance methods of the  
>>> class's
>>> eigenclass) is for most purposes an implementation detail. It adds  
>>> nothing
>>> to understanding to open the eigenclass inside the class's  
>>> definition in
>>> order to add class methods. It may save some typing, and it does  
>>> help when
>>> searching (as David) says. Nevertheless, I regard the practice as  
>>> a bit of
>>> an affection - 'look at me, ma, I'm opening the eigenclass!' - or  
>>> as the
>>> imitation of an affection. It confuses newbies to no purpose, and  
>>> confuses
>>> everyone when 'class << self' has scrolled off the top of the  
>>> screen.
>>
>> A lot of things confuse newbies. I don't think that's a very good
>> point for why you don't do something. #each confuses newbies, should
>> we also refrain from using that? Of course not.
>>
>> Educating people so they understand why and when it should be avoided
>> is better then raising a fire alarm (unless it's really a fire).
>> Contrary to your statement though, I don't use class << self to feel
>> special, and my ma could care less about how I code. ;)
>
> I thought it was just that
>
> class << self
>  def method1; end
>  def methdod2; end
>  def methdod3 end
>  def methdod4; end
> end
>
> becomes confusing as soon as those method definitions fill up a  
> screen.
> def self.method1 makes it instantly clear that it's a singleton  
> method.
> That's what I do and why I do it, anyway.

Surely, as soon as they scroll off the screen, it's time to factor  
that code off into a module or class of its own though?

It seems to me like whenever you have a lot of class methods on a  
class, you've got a new class dying to get out. It's like class <<  
self is like a little incubator for that new type!

Or Is that just me?



More information about the rspec-users mailing list