Friday, April 20, 2007

Ruby: Class Methods

It's very common when moving from Java or C# to be weary of Ruby's class methods. Many people have written about how static methods are evil in C# and Java, but do those arguments apply to Ruby?

Complaints
  1. Static methods cannot participate in an Interface. Ruby: No interfaces, thus irrelevant.
  2. Static methods cannot be abstract. Ruby: No concept of abstract, also irrelevant.
  3. Static methods are not polymorphic. Ruby: doesn't seem like it applies since you don't declare type in Ruby. Also, you don't access class methods directly from an instance.
  4. Static methods are hard to test. Ruby: Class methods are as easy to test and mock as any instance method. Perhaps this is because they are simply instance methods of the sington class.


At this point I ran out of complaints, but it's been over a year since I've touched C#. If you have complaints of your own that support or oppose this entry, please drop them in the comments.

Another thought about static methods is that they tend not to encourage proper object design. For example, a method that removes characters from a string is probably best served on the string itself.
class String
# an example class method
def self.delete(string, characters)
...
end

# a better instance method
def delete(characters)
...
end
end
You see this type of class method much less in Ruby since Ruby has open classes. But, it's good to remember to put methods on the object whose data is being manipulated when possible.

So what exactly is a class method?
class Parser
def self.process(script)
# ...
end
end

Parser.singleton_methods.inspect #=> ["process"]
From the example, you could say a class method is a singleton_method. Where do singleton methods live?

class Parser
def self.process(script)
# ...
end

def self.singleton
class << self; self; end
end
end

Parser.singleton.instance_methods(false).inspect
#=> ["singleton", "new", "superclass", "allocate", "process"]
Singleton (class) methods are actually all instance methods of the singleton class.

In fact, you can define a class method various ways, but the result is always an instance method on the singleton class.
class Parser
def self.self_process(script)
# ...
end

def Parser.parser_process(script)
# ...
end

class << self
def singleton_process(script)
# ...
end
end

def self.singleton
class << self; self; end
end
end

Parser.singleton.instance_methods(false).inspect
#=> ["singleton_process", "parser_process", "new",
"superclass", "allocate", "singleton", "self_process"]
Of course, the process method is also inherited by subclasses and the singleton classes of subclasses.
class Parser
def self.process(script)
# ...
end
end

class Object
def self.singleton
class << self; self; end
end
end

class HtmlParser < Parser

end

HtmlParser.singleton_methods.inspect
#=> ["singleton", "process"]
HtmlParser.singleton.instance_methods(false).inspect
#=> ["singleton", "new", "superclass", "allocate", "process"]
In a later post I'll talk about where those methods are stored in the underlying C code.

Thanks to James Lewis, Matt Deiters, and Mike Ward for help on this entry.

10 comments:

  1. Anonymous1:17 PM

    The problem I have with static/class methods are with some "programmers" that use them. I've worked with many "programmers" that do imperative programming via a ton of class methods while believing they are doing OO.

    ReplyDelete
  2. The real stumbling block is that Java class methods are totally different things from Ruby "class" methods, so different that applying Java rules of thumb to Ruby just isn't even relevant. If you can get a Java programmer to see the difference in what classes are, the class methods stumbling block vanishes.

    Didn't include C# because I have no experience with it, but I believe C# has an object/classes model virtually identical to Java's, so this may be equally relevant there as well. It's partly just that knowing OOP is very different from knowing Java's OOP, or Ruby's OOP. Ruby's OOP runs on a Smalltalk paradigm which is very different from Java's.

    ReplyDelete
  3. Anonymous4:00 PM

    Giles,
    I agree that static methods in Java are completely different than Ruby singleton methods. Unfortunately, people new to Ruby often mistake them for the same thing.

    ReplyDelete
  4. I know what you mean about C#. I used to follow the rule of no static methods, so even when a method didn't need instance variables, I would instantiate a useless object and call the method on that. I figured I was being "diligent".

    With Ruby I've embraced class methods. If a method uses no instance variables, then I make it a class method. Super easy rule to follow.

    ReplyDelete
  5. Re static methods are not polymorphic: rather than saying it's not revelant, I would say that class methods in Ruby are polymorphic. That's fundamental difference, as you mention later: class methods in Ruby are fully object-oriented, polymorphic methods of objects of type Class. In Java static methods are not even object-oriented, because they are not associated with any object; they're just like functions in a procedural language like C.

    ReplyDelete
  6. Anonymous2:34 AM

    The main problem with static methods are not their lack of polymorphism, etc but the faact that they encourage thinking about computation as behavior operating on data. This encourages the separation of the two and leads to thin objects which dont have behavior or miss whole new abstractions altogether. Of course all this is true only if you are working in a language with OO paradigm.

    ReplyDelete
  7. Unless I am mistaken, Ruby class methods are polymorphic. If you call 'self.class.foo', if no message is found, the message gets sent to the class object's parent.

    Class objects in Ruby (unlike Java) can have private instance variables (@) in addition to class variables (@@). Given that, why do they break the data + code abstraction?

    ReplyDelete
  8. Anonymous9:55 AM

    I like comparisons.. include as many platform as you want because it is interesting to find diffirentces..

    ReplyDelete
  9. Jay Fields,
    This is Srinidhi.I think it’s very good approach to make everybody understand about class methods and instance methods, however while I learnt this, some of my variable concepts got haywire and I m feeling very bad as how come I got into such basic doubts.
    Any way here is my problem in variables: Instance Var:
    class A
    @a=1

    def a1
    puts @a=1
    end

    def a2
    @a=2
    puts @a
    end

    end

    For this:
    x=A.new
    x.a1 == > nil # As expected as @a=1 defined is class level not method level. And once instance var is set in method it is reflected in all methods.
    x.a2 == > #@a is set to 2.
    x.a1 == > 2 # As expected.

    However if I use class methods:
    class A
    @a=1

    def self.a1
    puts @a
    end

    end

    For this:
    A.a1 == > 1 # OOOPS!!!! How is this possible. The instance var(@a) is set at class level, how did it enter method level. It should have been nil right, as per previous example.

    Also:
    class A

    def a1
    @a=2
    end

    def a2
    puts @a
    end

    end

    #lets create a child class B
    class B < A
    @a=”Srinidhi”
    def self.b1
    puts @a
    end

    def b2
    a=A.new
    puts @a
    end

    def b3
    puts @a
    end

    end

    For this:
    x=B.new
    x.a2 == >nil #Ofcourse it is nil as it is not yet set.
    x.a1 == > @a is set to 2
    x.a2 == >2 #As expected.
    x.b3 == > 2 #OOOPS!! How is this possible. @a is an instance variable , how did it pass across classes . If so why do I need to use a class var if instance var alone can achieve this job.
    x.b2 == > Also gives output 2. This is expected as I m instantiating A and thus calling all var values temporarily in that method
    B.b1 == > Gives “Srinidhi”.

    ReplyDelete
  10. Anonymous8:17 AM

    Srinidhi,
    I believe you're misunderstanding how instance variables are set. Also, when I run your example in irb I don't get the same results you have listed in the comment.

    Here are a few examples of how instance variables work and how the context in which they are defined makes a difference.

    class HasInstanceVariables
    def initialize
    @a_var = 1
    end
    end

    The above example is a class that will have an instance variable set when constructed. Notice that the @a_var is being set in the context of the instance, not in the context of the class.

    class HasSingletonClassInstanceVariables
    @a_var = 1
    end

    The previous example is setting an instance variable on the singleton class. This doesn't seem to be the behavior you are looking for.

    Lastly, here's another example of both types of variables within the same class.

    irb(main):039:0> class BothVars
    irb(main):040:1> @singleton_instance_variable = 1
    irb(main):041:1>
    irb(main):042:1* def initialize
    irb(main):043:2> @instance_variable = 2
    irb(main):044:2> end
    irb(main):042:1>
    irb(main):047:1> def self.singleton_var
    irb(main):048:2> @singleton_instance_variable
    irb(main):049:2> end
    irb(main):050:1>
    irb(main):051:1* def instance_var
    irb(main):052:2> @instance_variable
    irb(main):053:2> end
    irb(main):054:1> end
    => nil
    irb(main):055:0> BothVars.singleton_var
    => 1
    irb(main):056:0> BothVars.new.instance_var
    => 2

    ReplyDelete

Note: Only a member of this blog may post a comment.