I would like to ensure that some attributes of an object are unique
all the instances of that class.
So, I would like to prevent the creation of instances of a class that
attributes “equal” to the attributes of an already created instance.
(solely) As an example, the problem of creating an instance of a Person
class that has the same name of an existent instance.
My simple person class would be:
I found my way through overriding the Person.new method.
(Thanks “The Ruby P.ming Language” book).
So that the new instance is not even allocated if there’s already one
the same name.
- Could this be considered a poor design choice?
- What other ways to accomplish this?
Any opinions, tips, critics are welcome.
Some more comments:
Doing this way made me able to treat the object creation in a generic
The logic behind the uniqueness of the instances is hold by the class
itself, not by the (running) code.
This is desirable for me in this specific set because I’m parsing an xml
file with tags in a recursive manner.
I have a Hash that maps tags to classes.
The uniqueness attribute requirements of each class is different.
For example: Person unique by name. Telephone unique by number.
The parser only:
- Take the tag
- Look for the class that is mapped by the tag
- Create the class using the attributes and text as argument to new
- The class is the “when” and “where” the uniqueness validation is in
Thanks in advance,
My real problem is a little different (not Person or Telephone).
I used the Person class just as an example.
If someone curious about the code, tell me that I post the whole code.