Best way to do helpers for a constructor

What is the best practice for creating helper methods for a
constructor? In Java (not that I know that much about Java), my
instinct would be to make helper methods for a constructor be private
class methods, since they generally don’t rely on the state of the
object being created. In Ruby, however, it seems you’re not allowed
to call private class methods from within instance methods.

As a concrete example, here’s part of a solution I submitted for the
DateRange quiz:

class DateRange

def initialize(*args)

arr = args.collect {|rep| day_num(rep)}

arr.uniq!
arr.sort!

@string =  build_string(arr)

end

end

day_num should convert a representation of a day (could be a name,
abbreviation, or a number) to a day number

build_string should return a string representing the days in an array
of day numbers

My question is, how should I define day_num and build_string? It
doesn’t seem like they should be instance methods, since they don’t
rely on any state. I also want them to be private, since they are not
part of the class’s specified interface.

In ruby, however, private methods must be called with self as the
implicit reciever. Since initialize is an instance method, self is an
instance of class DateRange. When you send messages to an instance of
DateRange, they look in class DateRange, and then up the inheritance
heirarchy. Class methods don’t live in the class, though, they live
in the class’s metaclass, so they won’t be seen when a message is sent
to an instance of DateRange.

On the other hand, private class methods can be called from other
class methods, since inside a class method, self refers to the class,
and when messages are sent to the class, the first place methods are
looked for is in the metaclass.

In any case, what should I be doing?

Cheers,

Jason

On 9/5/06, Jason M. [email protected] wrote:

What is the best practice for creating helper methods for a
constructor? In Java (not that I know that much about Java), my
instinct would be to make helper methods for a constructor be private
class methods, since they generally don’t rely on the state of the
object being created. In Ruby, however, it seems you’re not allowed
to call private class methods from within instance methods.

But unlike Java, Ruby doesn’t have constructors, instead it has class
methods new and allocate which are rarely overidden.

The standard new method calls allocate to get storage for the instance
and then ‘sends’ initialize to the instance, using a non-standard
mechanism.

So I’d just make the helper methods private instance methods. Since
initialize itself is an instance methods it will work. There’s
nothing written in stone saying that an instance method should rely on
instance state.

IMHO this difference between Java and Ruby is a good thing. Ruby
doesn’t have “tyrannical constructors” as Martin F. put in his
article on Rake.


Rick DeNatale

My blog on Ruby
http://talklikeaduck.denhaven2.com/