Richard Turner
1/21/2005 2:59:00 PM
On Fri, 2005-01-21 at 23:36 +0900, David A. Black wrote:
> >
> > I'm new to Ruby
>
> Welcome!
>
Thank you :)
>
> At the risk of over-simplifying, let me try to simplify :-)
>
> Generally in Ruby you don't need or see too many methods with 'get'
> and 'set' in their names, since there are a variety of ways to perform
> those operations less verbosely. For example, you can define a method
> called [] and then use index-style bracket syntax:
>
> class Section
> def self.[](n)
> # here, a fetch command for record n
> end
> end
>
> record = Section[10]
>
> That would bypass the need for a constructor (if that's appropriate in
> your case).
>
That's great, but isn't that just a more succinct way of doing the same
thing? I.e. isn't this the same?:
class Section
def self.loadedFromDB(sectionID)
# here, a fetch command for record sectionID
end
end
What I want []() or loadedFromDB() to return is a Section, but I don't
want people to be able to call Section.new in error, otherwise they'll
not get what they think. E.g.:
secFromFactory1 = Section.getSection(10)
=> #<Section:0xb7f8d468 @index=1, @firstQuestionID=515, @name="Living
Arrangements", @sectionID=10>
secFromFactory2 = SectionFactory.getSection(10)
=> #<Section:0xb7f8d468 @index=1, @firstQuestionID=515, @name="Living
Arrangements", @sectionID=10>
BUT:
secFromNew = Section.new(10)
=> #<Section:0xb7f728e8 @index=1, @firstQuestionID=515, @name="Living
Arrangements", @sectionID=10>
See the object IDs are the same from the factory but different using the
constructor. So if I do:
secFromFactory1.index = 2
secFromFactory2.index
=> 2
BUT:
secFromNew.index
=> 1
In short, I've rather painfully created a factory method that, given an
ID, returns the correct object from a pre-filled set. However, I now
need to stop people using Section.new and I can't. This leads me to
believe that there may be a Better Way, but I don't know what it is :(
Cheers,
Richard.