| > How anyone could possibly be productive in such an environment. What is it that's so attractive about it to Smalltalkers? Now you've probably heard that in Smalltalk everything is an object. Sure its an nice catch-phrase but hard to grasp its significance. Consider then, that classes and methods are live objects within the Image. You can operate on them as you work within the live Image and from your application program. For example, the Pharo mail list was recently asked the following question...
> I want to have many different object instances with different
> behaviors picked at random from a list of available behaviors. What I had in mind was a functionality similar
> to prototyped languages like Self and Javascript in which you
> could change the behavior inside the object and not the class/prototype. A way to achieve this is to define each behavior as a normal method. For convenience, we'll define two protocols, 'behaviors' and 'non-behaviors' in the system Browser to hold these. For the uninitiated here is a short intro to the Browser. Protocols show in the third pane.
https://www.youtube.com/watch?v=zgQjcZ9SCCs The class MyObject is defined with an instance variable to hold which behavior to invoke... Object subclass: #MyObject
instanceVariableNames: 'behavior'
classVariableNames: ''
package: 'Example'
In the Browser, add these two methods to the 'behaviors' protocol... behavior1
Transcript show: '1'.
behavior2
Transcript show: '2'.
When an object is created, we'll set an object's behavior by asking its class for all its methods, selecting those that are in the #behaviors protocol, then from that collection making a random selection.In the Browser, add these two methods to the 'non-behaviors' protocol... initialize
| behaviors |
behaviors := self class methods select: [ :m | m protocol = #behaviors ].
behavior := behaviors atRandom selector.
perform
self perform: behavior.
Thats all that is required.To test this, from Playground (our REPL) evaluate...
Transcript open.
10 timesRepeat: [ MyObject new perform ]. ==> 2221212212 But how do I add new behavior at run-time you may ask? Now since classes are objects within the runtime Image, the application can ask the class to compile a new behavior. This is can be demonstrated by evaluating this code in the Playground... newBehavior := 'behavior3
Transcript show: ''3'' '.
MyObject
compile: newBehavior
classified: #behaviors
notifying: nil.
To test this, from Playground evaluate... Transcript clear.
10 timesRepeat: [ MyObject new perform ].
==> 211133212That flexibility is why I love Smalltalk. |
That said, you can get the same kind of flexibility in Lisp or even Lua, among others, and I'm having a hard time thinking of a use-case where such a thing would come in handy.