[prev in list] [next in list] [prev in thread] [next in thread] 

List:       ruby-talk
Subject:    Re: Singleton Class or Module Functions?
From:       Brian Candler <B.Candler () pobox ! com>
Date:       2004-10-21 8:15:14
Message-ID: 20041021081503.GA1232 () uk ! tiscali ! com
[Download RAW message or body]

> It seems the above two types of constructs can be used interchangeably. They 
> both have but one "instance". The both have the same access to methods. The 
> singleton has to be instantiated the first go around, but since that's
> behind 
> the scenes, that doesn't really make any difference (or does it?).

In the first case, the object *is* the module. In the second case, you have
two objects: a Class, and an instance of that Class.

I've never seen the need for or benefit of the second case, because to me a
Class is like a potato printer for making a bunch of objects which share the
same methods. If you're only ever going to produce one instance (and you are
enforcing that with Singleton) then there's little point in having a Class
in the first place.

You might as well just create one object directly:

  Foo = Object.new
  class <<Foo
    def hello
      puts "Hello, world!"
    end
  end
  Foo.hello

However, making Foo a Module is convenient because it gives you your own
namespace (e.g. for sticking constants in, or private helper classes). So as
long as the module name itself does not clash with another module, you can
be sure that everything else inside won't clash either.

Writing as a Class may make sense if there's any chance you might want to
create more than one instance in the future.

Regards,

Brian.

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic