Search code examples
smalltalktraits

Add trait to object at runtime in Smalltalk


For a small university project, I need to write an application in Smalltalk which simulates an award ceremony. Here artists and bands can be nominated to win an award. However, an individual artist can also be a jury member to vote for a nominee.

To enforce the restriction of artists who are not in a jury to not be able to vote, I was thinking of dynamically add a Trait to each artist object once they have been added to a jury. This then allows me to deal with method class appropriately.

My question now is, is it possible to accomplish dynamically adding Traits to an object? I already looked at How can I add methods to a class at runtime in Smalltalk? but is not really what I am looking for.

Regards

UPDATE 1 After adding the method on the class side, this works. However, when I wish to assign an artist to a jury I write something like:

kurt_cobain juryMemberOf: aJury.

then in the method juryMemberOf I add the (voting)artist to a list (to keep track of all the jury's he is a member of):

juryList add: (VotingArtist from: self)

When I then inspect juryList I indeed see I added VotingArtist objects to the list. However, the original Artist object in my Workspace hasn't changed into a VotingArtist. Not sure if this is possible but, later on I need to have the ability to write:

kurt_cobain votesFor: justin_bieber.

At this point in time I get a MessageNotUnderstood for the method votesFor which is normal since kurt_cobain is still an Artist object.


Solution

  • That's very hacky. You're problem can be solved using classic inheritance (which I'm not going to detail here, since it's homework). An artist with voting rights is simply a subclass or Artist. When you want to give an artist voting rights, change the class, e.g. VotingArtist from: self, where VotingArtist is the subclass of Artist. #from: could be implemented as

    VotingArtist class>>from: anArtist
        ^ self new copyFrom: anArtist