new String()
is a code smell - it is almost always unnecessary because of the immutability of String
. Once a String
instance has a value, that instance will never, ever have a different value.
In the following method, new String()
is redundant:
public static String string( final String string ) {
return new String( string.toLowerCase() );
}
toLowerCase()
returns a new (different) String
instance - new String()
doesn't do anything beneficial here other than cause another object creation having the exact value of the String
instance returned by toLowerCase()
Here's a small Groovy script showing the concept (I hope - note, this is Java under the scripting language):
String a = 'CamelCase'
String b = a.toLowerCase()
println "a='${a}'"
println "b='${b}'"
producing
a='CamelCase'
b='camelcase'
Note that a
didn't change - it is immutable; b
is a new String
value.
The same is true for BigDecimal.movePointLeft()
or any other method on BigDecimal
that returns a BigDecimal
- they're new instances, leaving the original instance unchanged.
OK, now to answer your question:
Having a set of operations for Strings
that perform a useful purpose in your application is a fine idea. Using a factory probably isn't necessary for something like String
, but might be for a different immutable class that takes some effort to construct.
In the case where it is not possible to extend the base class, like String
, a static method
s class as @kgiannakakis described is fine.
Otherwise, if the "immutable" class is part of the application, where you have access to the class declaration/definition, methods returning a new instance, in the model of BigDecimal
, String
, etc, would be preferable. This is in essence what @Erik Hesselink ,@Bruno Conde and @reallyinsane have said.