Best way to do helpers for a constructor

J

Jason Merrill

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,779
Messages
2,569,606
Members
45,239
Latest member
Alex Young

Latest Threads

Top