Object creation review

When working with OO languages we use constructors to instantiate our objects. Constructors should always return a valid instance ready to use, you don’t need to perform any additional task before using the instance. In some occasions an object need some collaborators to perform its work and in that cases you will need to provide a constructor that takes this collaborators as parameters.

The syntax of constructors may vary depending on the language, in C++like languages (Java, C# and others) constructors take the same name of the class. In cases like Object Pascal (the language behind Delphi) you use the keyword constructor to declare constructors. And finally  we have Smalltalk-like cases, where you constructors are simply class methods, no special name , no keyword, just call them as you like.

One practice I like when defining constructor is to give them some semantic, this is a very common practice for those who work with Smalltalk but it is not so common for those working with C++ like languages. Many times when I work with C# or Java, I find classes that provide several constructors with different parameters, but is not so clear how this constructors work, of course al of them return a valid instance, but do they perform any additional task? is there any particular property in the create instance? Let’s see an example to illustrate it. Let’s define a person class with first name (mandatory) and last name (optional).

In C# we could have something like this:

public class Person
public Person (string firstName) {…}
public Person (string firstName, string lastName) {…}

And to use it:

Person aPerson = new Person("John");
Person anotherPerson = new Person("John", "Foo");

In Smalltalk this could be:

Object subclass Person
Person class>>withFirstName: aFirstName.
Person class>>withFirstName: aFirstName andLastName: aLastName.

And we use it this way:
aPerson := Person withFirstName: 'John'.
anotherPerson := Person withFirstName: 'John' andLastName: 'Foo'.

As I said, this practice is very common in Smalltalk, but it can be used with C++like languages, in fact it is recommended by Kent Beck in his book Implementation Patters that is focused on Java. Let’s refactor the C# person class to use this pattern.

public class Person
public static Person WithFirstName(string firstName) {...}
public static Person WithFirstNameAndLastName(string firstName, string lastName) {...}

( I know, Smalltalk’s ability of merging method name and parameters provides a great user experience that is impossible to emulate with C++ like languages. )

One thought on “Object creation review

  1. ¡Muy interesante! Con este ejemplo sencillo se pone de manifiesto la potencialidad de Smalltalk, sobre todo la habilidad de manejo de mensajes y parámetros, como bien vos resaltás al final de tu nota.

    Este año tuve la posibilidad de asomarme al mundillo Smalltalk (aunque muy poco y más que nada en temas conceptuales, no de códificación)gracias a una capacitación que tuve en el trabajo, pero lo poco que ví me dejó con ganas de mucho más.
    Es por eso que tengo pendiente de lectura el libro “Smalltalk, Objects and Design” de Chamond Liu.

    También me parece muy buena la idea de introducir Smalltalk en la materia Algoritmos y Programación III de FIUBA.
    A pesar de haber cursado la materia en el segundo cuatrimestre de 2008 y de haber aprobado el examen final en la instancia del 2 de octubre de este año, sigo suscripto a la lista de correos de la materia. Me parece una buena manera de seguir aprendiendo y estando al tanto de los temas que allí se tratan.
    En un futuro me gustaría poder colaborar de alguna manera, obviamente con el objetivo de seguir aprendiendo.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.