A little black magic, making generic VW constructors

I have been playing with a little Smalltalk black magic to solve a philosophical problem. I believe that my acts should be consistent with my beliefs, not always possible not always what I want at the moment but …

So what is the problem?

I happen to be one of those Smalltalkers that creating setters and getters for every instance variable as a default policy just rubs me the wrong way. Now, please I don’t want to start the 20th billionth debate on this, but to me there is state that is just meant to be private really private and putting an accessor in front of one is like building a bathroom without a door. Not cool.

So then don’t create accessors for everything , you may say?

but how many times do we see instance creation methods i.e. constructors where we do this type of stuff:

MyClass>>>newFor: this and: that
inst := self new.
inst this: this; that: that.


^inst

In this case we need the instance side setters #this: and #that:

Alternatively we could do something like:

MyClass>>>newFor: this and: that
inst := self new.
inst newFor: this and: that.

^inst

Here, I don’t have to create the accessors and therefore leave my instVars private but I still have to create an instance side method to field the incoming args used in the construction of the instance. Annoying, but worse it still does provide a mechanism to mutate instance variables that are meant to be private albeit one can’t just mutate one.

Recently one night I was bored and just decided to come up with something no matter if it was ugly or bad, brainstorm something into creation.

I decided on the following requirements:

  • a generic constructor i.e. a message where I could pass an array of instance variable names / value pairs.
  • only allow for every respective class to be the sole constructor of its instances in this manner

The result would then look something like this:

MyClass>>>newFor: this and: that

” e.g.:

self construct: {‘this’->this. ‘that’->that.}

Now, what the heck is that {stuff …}.

That is, if I recall correctly, something that was borrowed from Squeak by Cincom’s Vassili Bykov and its called Brace Constructors. Don’t have time to get into it right now but it basically one can delimit objects with periods i.e. $. So for example one can do the following:

{1. 5+2. true. self calculateSomething}

Anyhow , back at the ranch.

I’m sure that this looks very strange to most Smalltalkers and I’ll admit that I’m not totally sold yet although it really is convenient. So far so good . I may end up liking it.

Note that the following will not work:

MyClass construct: {‘this’->this. ‘that’->that.}

An exception is raised stating that only “MyClass” can send #construct:.

In the next installment of this article I will cover how that is done and the pros and cons.