Leandro Caniglia
Leandro Caniglia

Reputation: 14843

What's wrong with Class instances?

It would be good if someone could explain why, in Smalltalk, the expression

class := Class new
  name: 'OurClass';
  superclass: Object

is not appropriate for creating a new class. More precisely, what's wrong and what's right when an object like class attempts to act as a normal class? Can it create instances? Can it compile methods? What can't it do?

Upvotes: 3

Views: 100

Answers (1)

blihp
blihp

Reputation: 675

You don't specify which Smalltalk dialect you're working with (this doesn't work in Squeak or Cuis, for example) but I'm going to assume it's Pharo as it does execute without error there. In Pharo, it actually does appear to create a new class which surprised me... in other Squeak dialects I don't think it will even remotely do what you want it to. So the first issue is it's nonstandard, but that's relatively minor...

Let's assume, for this discussion, that your example code were supported across Smalltalk dialects and did exactly what you wanted it to: create a new class OurClass as a subclass of Object. The larger issue is that what you've created is essentially an island that is disconnected from the rest of the Smalltalk environment because you've bypassed all of the Smalltalk metadata/metastructure. So you can't do something as simple as open a browser window and find 'OurClass'... the rest of Smalltalk doesn't know about it. Things like OurClass new won't work. Your new class is also not rooted, so if you discard the class variable from your example, the class will disappear. This also means that it will not be part of any package and your class definition would not be saved out with the rest of your source code. There are probably other surprises you'd run into as a result of doing things this way (i.e. the debugger might choke on it etc.) So for general purpose class creation needs, what's wrong with it? Just about everything.

That said, there is one use case where you might legitimately want to create classes this way: metaprogramming. A valid metaprogramming use case would be to create an anonymous class where you have a need for exactly this 'disconnected' type of behavior and need a class temporarily/internally but don't want it to ever be seen/used by the rest of the Smalltalk environment. As long as you really want and need to do things this way, I'd see no problem with it. The few times I've needed something like this (never done it exactly this way, but close) I've been sure to document it very well because it's not the sort of thing you're likely to remember 6 months later what you were doing or why... let alone another programmer. For metaprogramming where you've got a specific need and this is the right tool for the job, what's right with it? Just about everything.

Upvotes: 2

Related Questions