Tuesday, March 14, 2006

How useful is String(String) constructor?

Good architectural design is essential. We can not expect junior programmers to know all APIs well. With good design good programming practices can be enforced and unintentional mistakes avoided. Architect’s and designer’s responsibility is to create a framework of interfaces, abstract classes, utility classes that other developers will use or implement.

Recently I came across this line

String value = new String(“some text”);

I have not seen String(String) constructor for a long while. Have you seen it recently? Probably not. And there is a good reason for it. For 99.9% of cases you won’t need it at all. It only serves as a copy constructor that takes a String as an argument and creates a new instance that represents the same string of characters. Further more first string created (“some text”) is ready for garbage collection on the very next line. It would only be useful if you were to compare the two strings as

someString == someOtherString

Generally, when I see such comparison it is a programming bug. In most of the cases the equals() method is used for String comparison.

someString.equals(someOtherString)

But that is another story. Anyway, back to String(String) constructor. Having this constructor may lead to unintentional object instance creation. When you create a String by putting anything between double quotes you already have an instance. There is no need to call new String(String). The following line will perfectly do the job.

String value = "some text";

I understand that the designers’ intention was to have a String copy constructor, but in this case, I do not believe, it was a wise step. A factory method would have been better. It could be called createNewInstance(String) or copy(String).

Good design is essential. But good design is not bullet proof. We still need to know the APIs, frameworks and things such as immutability of String objects.

2 comments:

Kat Marsen said...

First of all, string constants are never garbage collected. Second of all, string constants are intern'd, which means they are shared across the entire VM. This saves memory. But it is not always what you desire.

The copy constructor on String allows you to create a private String instance from a String literal. This can be very valuable for constructing meaningful mutex objects (for the purposes of synchronization).

Beta said...

Nowadays also permgen space is garbage collected (Sun JVM). So string constants may be removed too.


Creative Commons License This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License.