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. )