small talk programming tutorial2

3. Main Differences between Java and Smalltalk

3.1 Java Versus Smalltalk

What are the point of contact of Smalltalk and other languages such as C and Java? Smalltalk is executed using a Virtual Machine (VM) as Java. The VM has a very complex Garbage Collector (GC) very similar to the HotSpot. And the Smalltalk code is stored in a byte-code form. But Smalltalk holds all the code in only one file (the image) and store in it all the state of the system (working Threads and so on). The image is coded in a binary-independent format (as java .class files) and can be ported across different platform. For instance, Squeak can run on Macintosh, Unix, OS/2, Ms-Dos, Windows 9x/NT/2000, and Windows CE. Even, it is easy to port the VM to other platform, because is coded in C language.
The Entire IDE, and the GUI are written in Smalltalk, mostly using the MVC (Model View Controller) design model.
Even the Java Swing uses a MVC-like model. Squeak has even a best and powerful GUI, called Morph. See the figure Morph.

The Smalltalk IDE uses reflection for exploring itself in a very massive way. For example, writing a Proxy object is trivial!!
Every class should have a comment: like in the Javadoc, you can integrate the documentation in the code! Squeak can create even hyper-link between two line of code or two comments!
About namespace: before the 1999, the concept of name-space wasn't implemented in the commercial versions of Smalltalk. For instance, in Squeak all the global objects are stored in a object called Smalltalk. VisualWorks 5 provide namespaces, and Squeak has a similar way for isolate projects code.

The Gui, the Network and the Sound.

Exploring the big Squeak library is impossibile in this small tutorial, because of its size. But I'd like to show you only a small idea of some of the applications you can use:






 Morphic: not only boring widgets!
With Squeak, and in less of 7Mb of image, you get a Email reader (Celeste), a Flash reader, a small Web browser (Scamper) a dynamic web server (PWS) and a special 3D library (3DBalloon) integrated with the Alice Authoring Tool http://www.alice.org. And even for music, you can play midi, digitalize sound and so on!
Note: The base Java 1.3 library is about 12Megabytes (uncompressed) without an ide or sound support!
The reason is simple: the .class format need to explicit say to the Java-VM what other classes it needs, for dynamic link. This is add a lot of redundancy. For instance, if you compress the rt.jar file, you get 4.3 Megabytes (ratio 65.6%). If we try to gzip the Squeak image, we got 3.10Mb (ratio 53.7%). So the Smalltalk image has less redundancy!

3.2 Types? No thank you!!

When you program in Java, you use types. You use int-s, floats, classes and so on.
We have seen a Class can be a nice place to put a struct. In Java, you often need to do a cast from a type to another. This is very common, and no one has trouble. In Smalltalk, the Virtual Machine only understands objects. If we execute 1+2 the VM of Smalltalk search the method + in the object 1, instance of the Number class. If Smalltalk do not found the method, will throw a Exception at Runtime
Exceptions are defined in ANSI Smalltalk. Some Smalltalk implementation may not have Exception, but can raise Errors.

The language-designers say type are userful, because the compiler can produce efficient code if it knows the type we are using (the sum of an two numbers is fast if they are integer and not float!).
Someone thinks type are userful to human-programmers, but in my own opinion, after two years of Smalltalk programming, it is not-so-true.
So, let's start to see how to program without type (and without casts...or other magic powers...)

3.3 The Squeak base library compared with Java

This is a small overview of the base library of the Squeak 2.8.
First of all, suppose you have a unordered collection, and you want to eliminate duplicates. Doing this in Java is boring, in Smalltalk is quite easy:


|uc unq|
uc:=OrderedCollection new. 
uc add: '2' ; add: '1'. 
uc add: '3'; add:'3'. 
unq:=uc asSet.

If print unq, you get:


Set ('3' 1 '2' )

Now you can sort it simply using:


unq asSortedCollection 

obtaining:


SortedCollection ('1' '2' '3' )

The large base library of Smalltalk can manage in this way complex data structures.
If you want collect items, try this:


|c s|
c:=OrderedCollection new. 
c add: 1 ; add: 1. 
c add: 2; add:3; add:4.
s := c select: [:i| i <=2 ]. "[*] Collect items < 2"
Transcript cr; show: (s asString) ; cr.

Obtaining:
OrderedCollection (1 1 2 )

First, we create a collection with five elements (1,1,2,3,4). Then the collecion c is filtered to just the elements less than two (in line [*]). The Collection classes implements also a reject: message, which is the logial inverse of select:.

3.4 The Smalltalk Code database

As you see, all in Smalltalk is written in Smalltalk! Not only the Smalltalk compiler is written in Smalltalk, but even the database holding the classes in the System is written in that language. A special dictionary, called Smalltalk, is a good starting point. Inspect it with:
Smalltalk inspect.
The Smalltalk Dictionary contains a reference to ALL the class on the system. If you want know how much classes the system has simply print:


Smalltalk size.

I have got 1193 classes on my Squeak 2.8 You can ask to the classes about their life and structure! Try for example:


( (Smalltalk class) inheritsFrom: Object) inspect.

We ask if the class of Smalltalk (SystemDictionary) is a subclass (inheritsFrom...) of the class Object, and we get true as answer.
Now open a browser with:


OrderedCollection browse

and click on the '?' button for getting the comment of the class. I suggest you to explore these clases: String, OrderedCollection, SortedCollection, Dictionary, Set. The Number class is also good for understanding how Smalltalk works with numbers.

Metaclass structure

There is also a dictionary for undeclared elements:

Undeclared inspect.

The Behavior class is used for describing the objects. The Hierarchy is like this
ProtoObject ()
        Object ()

                Behavior ('superclass' 'methodDict' 'format' )
                        ClassDescription ('instanceVariables' 'organization' )
                                Class ('subclasses' 'name' 'classPool' 'sharedPools' 'environment' 'category' )
                                        [ ... all the Metaclasses ... ]
                                Metaclass ('thisClass' )
                        Oop ()
                        Unsigned ()
In Smalltalk, Classes and instances are objects, and share some common properties. This is not true in Java, because static methods cannot have all these properties. The 'class' method give us the class of an object; and also classes can resppond to 'class' method. But...wait a moment, what is the class of Class? It is Metaclass:
Metaclass:
Metaclass instances add instance-specific behavior to various class-describing objects in the system. This typically includes messages for initializing class variables and instance creation messages particular to a class. There is only one instance of a particular Metaclass, namely the class which is being described. A Metaclass shares the class variables of its instance.
Look at this table:
#|   Expression                     -> Output
------------------------------------------------
1 |  (Object new) class             -> Object
2 |  Object class                   -> Object class 
3 |  Object class class             -> Metaclass
4 |  Object class class class       -> Metaclass class
5 |  Object class class class class -> Metaclass
5'|  Metaclass class class          -> Metaclass

Note: 5 and 5' are the same.
The trick is in the 5th expression. We should define MetaMetaclass for the 5th output. For avoiding this infinite recursion, Smalltalk overlap 'Metaclass' and 'Metaclass class'.


[Subtle] In general, the superclass hierarchy for metaclasses parallels that for classes. Thus,
        Integer superclass == Number, and
        Integer class superclass == Number class.
However there is a singularity at Object. Here the class hierarchy terminates, 
but the metaclass hierarchy must wrap around to Class, since ALL metaclasses 
are subclasses of Class. Thus,
        Object superclass == nil, and
        Object class superclass == Class.

3.5 Multiple-Inheritance

Smalltalk only supports single-inheritance, as Java. Java uses the interfaces for implementing a less strong interface inheritance. In respect of C++, interfaces can be thinked as pure abstract classes.
In Smalltalk you do not really need multiple-inheritance: you can share a set of protocols between classes. You can think protocols as set of methods. This give you a very powerful freedom: you can reuse code with similar meaning! Best, doing refactoring and improving code is simpler. In Java, if you want to add a method to an interface, you must implement it in all the implementing classes. In Smalltalk, you can do a smart thing: you can build a default implementation in a superclass (for instance Object) and reimplement only where it is really needed! Even if the code is not valid for every Object, it will work if correctly needed. Smalltalk will not stop you: if you know what you are doing, you will get maximum power.
But be careful: this freedom can produce very ugly code, so you must follow good programming pratice. The lack of interfaces and namespaces has been fixed in VisualWorks (see References). Squeak will provide a similar function in the future.





No comments:

 
Top Blogs