On Wednesday, October 20, 2004, 11:36:59 PM, rdlugosz wrote:

> Another option (which I'm betting won't be popular here...)
> would be to have a separate RectangleBuilder class that will make Rectangles
> for you.  You could have multiple methods here that would take reasonable
> parameter sets based on their name.

The last serious Ruby project I worked on used a similar approach.  It
was constructing something serious.  Can't remember what; let's use
Rectangles.

  class Rectangle
    attr_accessor :x1, y1, ...
    ...
  end

  class Rectangle::Generator
    ...
  end

  class Rectangle::Generator::Parameters
    attr_accessor :x, :y, :rx, ...
  end

Usage was something like:

  rect = Rectangle.generate { |p|
    p.x = 5
    p.y = 10
    ...
  }

The Rectange::Generator is justified if there is significant logic
concerned with generation - i.e. not just setting attributes.  The
Rectangle::Parameters provides an opportunity to clearly document the
parameters used for generation.

The upside of this is that the Rectangle class was short and sweet;
all the behind-the-scenes logic was nicely tucked away.

The downside is that a single mode of generation might be entrenched.
As Eivund has pointed out, different "factory methods" (or "generators",
or "constructors") can conveniently do different things.

The above approach is obviously overkill for a simple rectangle, but
for really complex objects it's a pattern I'm sure I'll use again.

Cheers,
Gavin