From: "Abinoam Jr." Date: 2011-02-28T05:30:18+09:00 Subject: Re: Ensuring uniqueness of an object at creation time Hi Gary, It's pretty elegant using a name such as "find_or_create" for the factory method. It really describes its behavior much better than "new". And setting "new" as private, good point too. In my specific piece of software I just have to make all the class a "find_or_create" method, even if it doesn't have any uniqueness constraints. This is because my parser is "agnostic", so I don't want it to decide where to use "new" or "find_or_create". It has just to use "find_or_create" in every object it tries to create. Thank you for your comments, Abinoam Jr. On Sun, Feb 27, 2011 at 4:13 PM, Gary Wright wrote: > > On Feb 27, 2011, at 3:00 PM, Abinoam Jr. wrote: >> a = :prepare_b >> b = :prepare_b >> >> With Symbol, if it has the same value, it's the SAME Symbol, not different ones. > > Don't get hung up on using the default new/initialize framework.  You can define your own constructors that return existing instances instead of allocating a new instance if you want to model 'value' semantics. > > message = Message.find_or_create('message_a', other, args) > > Then define find_or_create such that it manages a cached collection of messages that it can dip into if it finds a match or it can create a new message if necessary. > > In general I think it is better to define your own constructors if the 'normal' semantics of new/initialize aren't what you want instead of redefining new.  You can always make new private if you want to 'force' the use of your own constructors. > > If the only attribute of your messages is their unique name, then symbols might be exactly what you need but be aware that symbols are generally not garbage collected so that if you create them based on external data you might be opening yourself to a memory exhaustion attack (i.e. the attacker can cause your memory footprint to grow without bounds). Whether this is a concern or not just depends on where the external data is coming from. > > Gary Wright >