If you want to create an object in Java there is only one way: use a constructor.
Constructors in Java are different from all other methods. They don’t have a return type and can’t be invoked, only using the new keyword. Other tasks performed by constructors are:
- Initialisation of class variables
- Call the default contructor of the superclass if no constructor is present
- Initialisation of instance variables
- Execution of constructor body
Here is a common example of a constructor in Java:
If you want to create an immutable object in Java you need to have a constructor to initialise the final fields. Lets look at another example:
Immediately a problem becomes clear… if you read the code you have absolutely no idea what all the arguments mean. What is 200? What is 95.0? We have to look at the API or open the code of Person to see what arguments we can supply or have been supplied. Thankfully there is a design pattern that solves this problem, the Builder pattern.
The builder pattern is an ‘object creation software design pattern’. It can be used to create a immutable objects in a fluent, readable way.
Reading this code is much clearer, we don’t have to guess what the arguments mean, it is crystal clear. So we’ve got a good solution, right? Well, not really, I’ve got a big problem with the Builder pattern. For a simple immutable object as the Person above with just six fields we need the following code:
Woah… that is a stupendous amount of code just for a better readable immutable way of object construction. I don’t have a good solution for this problem, the Java language doesn’t have a good way to construct objects (especially immutable objects) in a readable manner. Constructors end up having a lot of confusing nameless arguments; or you’ll have to write a huge Builder class with a nice fluent interface.
The Java language is constantly evolving and there are now proposals to add ‘value types’ in Java. Reading through the proposal it seems the only way to construct the value type will be using the constructor, but I’m afraid this will quickly become a burden again. I’d love to have a better way to construct objects and (in the future) values, although I have no idea what it should look like. I’d love to have a fluent way of object creation without having to code a big Builder class, preferably in the language itself.
Would it be possible to change to language in a backwards compatible way to allow this?
One possibility would be to ‘steal’ from other languages, for example Moose Perl:
This has the readability advantage and has the flexibility of the Builder pattern (not needing dozens of overloaded constructors).
Would something like this be a good addition to the Java language?