First Law of Classes

I was introduced to Ruby by a charming German girl called Ulrika. She
was writing Watir programs for a vendor product.

On an old computer, I just found a program she had written. It scripts a
quote-and-buy insurance web site.

She has a ‘main’ program that calls a class that contains a series of
procedural methods working through the screens. Apart from that she has
a class that generates random input.

As a procedural program it is perfectly readable. However both of these
two classes contain no class or instance data. They either refer to
globals or receive parameters.

Now I think there ought to be a rule that a class is not a class if it
only has methods. It might be a module if you want to wrap it neatly.

If you saw a class without persistent data, would you be suspicious?

On 10/20/2010 03:37 PM, Mike S. wrote:

If you saw a class without persistent data, would you be suspicious?

Maybe, but there are good uses:

  1. instance as unique token

    STATUS_OK = Object.new
    STATUS_FAIL = Object.new

    result =
    begin
    # try something
    rescue
    STATUS_FAIL
    else
    STATUS_OK
    end

  2. flyweight pattern

    class PseudoRandom
    def initialize
    # set up seed, etc.
    end

    def next
    # get number from seed
    end
    end

    class Random
    def next
    # get number from /dev/urandom
    end
    end

    This method accepts either of the above classes.

    Even though Random has no state, it supports the same

    interface as Pseudorandom.

    def get3 cl
    seq = cl.new
    [seq.next; seq.next; seq.next]
    end

Mike S. wrote in post #955941:

Now I think there ought to be a rule that a class is not a class if it
only has methods. It might be a module if you want to wrap it neatly.

Technically, if it’s just procedures with no mixins, there’s no
particular reason for it to be a module either.

example 1

module Foo
def self.foo
puts “Method in module”
end
end

example 2

Bar = Object.new
def Bar.bar
puts “Method in object”
end

Foo.foo
Bar.bar

If you saw a class without persistent data, would you be suspicious?

Not really. A class is_a module anyway. It’s neater to use module just
to document that you don’t expect any instances to be created.

I would avoid the global variables though, and instead use instance
variables of the class/module/whatever container. That makes them a bit
less ‘global’.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs