Archive for October, 2006

Got Class?

Tuesday, October 31st, 2006

In Object Oriented languages, the class is the definition of a kind of object. Classes are arranged in tree-like hierachies with the roots of the tree being very general and the leaves being most specific. So a dessert is a kind of food, and cake is a kind of dessert. Because the class serves as the definition of an object, it makes sense that objects are created by using the class as a template. In other words, classes are used to create objects of the class’s type.

All of the languages discussed so far, C++, Java, Smalltalk, and Objective C have the notion of a class. What is different is how the languages represent the class itself.

C++ has no runtime representation of a class at all. Instead, all class information is soaked up by the compiler and represented using standard functions and globals with the class name prepended to their “local” names. The way a programmer designates a function as belonging to a class is to declare it within the class’s declaration using the very overworked keyword ’static’.

class CPlusPlusClass : public BaseObject
{
public:
static void classMember(); // declare the function

}

void CPlusPlusClass::classMember() {…} // define the function

CPlusPlusClass.classMember(); // really just a long name for a global function

Ditto for class variables. There’s no such thing in C++ really. Instead the language fakes it by letting you declare the variable in the class declaration’s namespace and in the end what you’ve got is a global with a very long name. Since there’s no class object, there’s no “this” variable and no way to do anything the least bit object oriented in class methods without explicitly naming super classes.

There’s also no built-in way to abstract object creation. When one wishes to create an object in C++, one uses the ‘new’ operator in conjunction with the class name, which coincidentally is also the required name of the initialization function. So in C++ we write:

BaseObject *c = new CPlusPlusClass();
Notice that here – at the moment of object creation, it is necessary to reveal the actual type of the object. If one desires a more abstract method of instance creation, it is necessary to adopt a factory idiom. Of course, converting to a factory creation mechanism from the use of operator new requires extensive modification of code, similar to the extensive work required to handle a new kind of exception.

Smalltalk takes the opposite extreme. Classes are represented as regular objects and are arranged into an inheritance hierarchy. The special variable “self” refers to the class object itself and ’super’ refers to the object that represents the classes superclass. Smalltalk class methods exhibit full polymorphism and class variables are made available to class methods and instance methods in the class’s instances. The Smalltalk class takes responsibility for instance creation and is thus a factory by default.

For instance, in the Squeak implementation, ImageReadWriter is an abstract class for reading and writing image files. Concrete subclasses exist for JPEG, GIF, PNG and so forth. The abstract base class makes use of class hierarchy navigation to find the correct subclass to render the image data. It looks something like this (error handling omitted):

“Find the first subclass that claims to be able to understand the binary stream’s data”

readerClass := self withAllSubclasses detect: [:subclass | binaryStream reset. (subclass new on: binaryStream) understandsImageFormat].

“Instantiate a reader from the class”
reader := readerClass new on: (binaryStream reset).

“Return the image from the reader”
^reader nextImage.

The beauty of this approach is that one can always write a new subclass of ImageReadWriter for a new image format and the new format is instantly supported without having to deal with registries or factory idioms.

Techniques like this demonstrate the power of using the object paradigm to represent classes.

Objective C uses a similar approach to Smalltalk with a couple of odd constraints. Objective C class objects lack support for class member variables. Instead one fakes it with static (as in C variables with internal linkage) variables. Also, Objective C performs lazy loading of libraries which means that not all subclasses are necessarily present at any given time. So the subclasses trick is a little hard to perform.

On the other hand, Objective C uses the same object creation mechanism as Smalltalk. So its still possible that the actual class of the object is not the same as the class that created it for you. Thus, the power of using objects to represent classes is mostly preserved.

Java’s approach is closer to C++ than to Smalltalk. While Java has ‘objects’ of type java.lang.Class for representing classes, these ‘objects’ have more in common with C structs than with objects in any other sense. Object creation is not performed by the class. Rather Java slavishly copies C++’s use of operator ‘new’.

Java also makes use of a ’static’ keyword to denote ‘class methods’. But these ‘methods’ are actually nothing but functions with long names. In fact, its not possible to do anything polymorphic in a class method. There isn’t even a way to get ahold of the class object representing the class.

public class A
{
// something that doesn’t work – no ‘this’
static void printClassName1() { System.out.println(”"+this.class); }

// this doesn’t work either
static void printClassName2() { System.out.println(”"+getClass()); }

// this does – but in subclasses it will be wrong
static void printClassName3() { System.out.println(”"+A.class); }
}

So crippling is the decision to not provide proper class objects, that the Enterprise Java Bean designers found it necessary to simulate class objects with the notion of “Home” objects. The “Home” object is intended to provide the ability to find existing objects or create new ones for a given class. This is definitely behavior that would ordinarily be put into a class object.

If we had one.

Happy Halloween

Tuesday, October 31st, 2006

Today is my favorite holiday of the year.  Halloween is a lovely mix of tradition (pumpkin carving, parties, trick or treats) and creativity.  The challenge is to celebrate in a completely new guise every year and I always love the challenge of coming up with a new costume.

A great example of mixing old and new is these photo-realistic pumpkin carvings.   Pretty dang cool.

A-Z Countdown Begins Now

Wednesday, October 25th, 2006

I just gave my 2 weeks notice.  Thus I begin the leap from software project management to full time Smalltalk developer and small business owner.

Exciting times. Last day – 11/9

At the Dynamic Languages Symposium

Monday, October 23rd, 2006

Which kicked off with a bang with Ian Piumarta’s COLA family/project. It seems he has distilled the machinery required to implement objects with late binding into a half dozen operations and a couple of “things”. Then, starting at this level begins building back up to existing dynamic languages – but since everything is implemented in a tiny kernel of primitives, the results are tiny and profound.

After that talk, many of the other talks were just dull and seemed so last century. For instance, the talk on PyPy, a Python implementation written in a subset of Python with code emitters targeting C, Java, and .NET, felt like a huge regression – Squeak did that 10 years ago – now COLA seems to be the next step while PyPy seems to be going over old ground. In fact, it seems the COLA strategy is likely to yield a smaller, faster, and more portable implementation with more powerful introspection.

Painters

Friday, October 20th, 2006

About three or four years ago, I was playing around with a concept I called Bricks. It was a way of factoring drawing operations out of UI components to make it easy to create new looks. The drawing operations were encapsulated into objects called Painters. I was doing it in Squeak using Morphic. It looked like this:

It must have been a good idea because I just ran across something similar from the Java Swing people.

So I’ve decided to dust it off and pick it up again. There have been a lot of changes in Morphic and I’ve given up on reworking the event deliver system, choosing to work with Morphic’s system, warts and all. I still think splitting drawing and layout will be valuable.

IE7 Launches (Yawn)

Thursday, October 19th, 2006

And the early reports are that it is dog slow and has trouble with AJAX style pages.  Just like IE6 I guess.  Meanwhile, Firefox2 is out and is kicking the pants off of IE7 in speed and web standards adherence.

Time for Microsoft to exit the browser game.  They have no talent for it and I, for one, will no longer invest any effort into making sites work with it.  Instead, I’ll be including a  Get Firefox Now link on every page.

As to Scoble’s comment “If there’s a way to do AJAX that works well in both browsers, why not do that? The virtualearth.com team found some way to do that.” The answer is that it costs time and money and I don’t have any extra of either.

Message to IE team: Get faster! Get compliant! Or Get LOST!  I have no time for you.

OOPSLA Dynamic Languages Symposium

Wednesday, October 18th, 2006

I’ll be in Portland from Sunday afternoon through Wednesday morning for bits of OOPSLA and to rub shoulders with other Smalltalk fans.  Contact me via tblanchard at mac dot com if you want to meet up.

Sanskrit, Smalltalk, and Fireworks

Sunday, October 15th, 2006

There’s a combination I won’t soon forget. I spent yesterday evening at the Santa Cruz home of Dan Ingalls celebrating the 10th birthday of Squeak. Dan showed a video of a lecture he gave with his father on the development of an OCR system for recognizing Sanskrit text.

A number of very interesting people attended including some folks from Argentina who are marketing a Smalltalk based oil field production planning system. Also in attendance were David A. Smith – a leading architect of Croquet, Andreas Raab, Craig Latta who is doing some amazing work on a Smalltalk based system called Spoon, and a number of other thoroughly interesting people too numerous to mention here.

As a bonus, there was a fireworks display which we viewed from Dan’s terrace. It’s always interesting when a bunch of smalltalkers get together, they can be such an eclectic bunch.

I Love You – Now Change

Monday, October 2nd, 2006

Which company would you prefer to invest in?

Company A:

“Our company is a dynamic organization with the agility to quickly adapt to new market conditions.”or

Company B:

“Our company is stable, well structured, and organized. What we are doing now is a perfect basis for everything we will do in the future.”(Sounds a little like the Bush administration)

The dynamic organization that can change quickly is going to be more successful than a static organization that is set in its ways.

So how come the software industry pundits continue to try to push static programming systems over dynamic ones when dynamic systems are generally more successful? Its senseless.

In C++ and Java, the assumption is that the superclass designer knows best. Whatever interface the original developer has exposed is expected to be the perfect and complete interface for all time. There is no way to extend an existing interface without owning the source code to it.

The implementation, it is recognized, might not be exactly correct in all cases, so the implementation is left open to extension via the one mechanism made available – subclassing (maybe – Java actually allows the most arrogant developers to forbid subclassing via the ‘final’ keyword).

The problem with leaving only subclassing is that subclassing, by itself only provides for extension of the system, not for modification. Fans of Robert C Martin or Bertrand Meyer might recognize this as The Open Closed Principle. Sadly, The Open Closed Principle is only works if you happen to work for a static company like Company B.

The harsh reality is that organizations are organic – they evolve and grow to adapt to new environment conditions. Failure to evolve is death. How can you modify your organization if the software that runs your organization is closed to modification by design? Worse, the underlying tools and technology on which your software is built actually work to enforce The Open Close Principle.

So how else to evolve your system? Objective C has a construct called a Method Category or more commonly just “category”. A category is a collection of methods for a class that may be loaded dynamically – or not. These are collections of additional methods to be added to existing classes. These additions may be made part of the organizations core software assets, or they can be application specific extensions that are too specialized for general consumption.

For instance, a web services application may find it convenient to add some methods to the string class for parsing up web requests, but the billing system doesn’t need this category of methods and so doesn’t bother to load it.

Categories can also make adapting an existing class to a new protocol easy. Not having a number of separate adaptor classes all over the place keeps the number of classes low and the conceptual size of the application architecture smaller.

Finally, categories can allow the user of a class to replace a buggy or inappropriately implemented method with a new implementation without having the source code.

Another useful tool is the ability to replace one class with another. The Objective C tool for this is known as “posing”. One writes a subclass of the original class and then says

[NewClass poseAs: [OldClass class]];

Now saying [OldClass new] actually constructs an instance of NewClass. This can be handy for sneaking superclasses into the class hierarchy and also for debugging around code you don’t own.

Using these techniques, along with message forwarding and delegation, subclassing takes a back seat to application assembly and drops from the most used tool to the mechanism of last resort. After all, its much better to simply arrange the classes you already have into the right structure than to create entirely new code with entirely new bugs.

Smalltalk has similar mechanisms and results in similar designs. Method categories exist and can be loaded as packages. Posing is done quite easily by replacing a class in the Smalltalk class dictionary with another class and executing a become: on all of the old classes instances. Its easy to insert new classes anywhere in the hierarchy and all of the code is easily accessible and modifiable. Subclassing in Smalltalk application development is a relatively rare event.

Of course, if you’re sure you know what you’re doing – perhaps Java and C++ are the right languages. If you’re sure, that is.