Java doc says String.trim()
Returns a copy of the string.
I have below code in my method, it does trim
as mentioned and results in creating new string thrice.
String foo = getFoo(storedProcedureResult);
if(foo !=null && !foo.trim().isEmpty()){ // --> creates new string
if(foo.trim().substring(1).equals("bar")){ // --> creates new string
} else if(foo.trim().substring(4,6).equals("bar")){ // --> creates new string
}
}
I made an attempt to minimize this with below code:
String foo = getFoo(storedProcedureResult);
if(foo !=null && !(foo=foo.trim()).isEmpty()){ // --> creates new string only once
if(foo.substring(1).equals("bar")){
} else if(foo.substring(4,6).equals("bar")){
}
}
Now, Sonar reports Assignments should not be made from within sub-expressions
. How do I efficiently minimize the usage of trim
in my method? I am bothering because this method is being used in production and invoked 250+ times per second and should not create more String
objects unnecessarily.
You can write:
String foo = getFoo(storedProcedureResult);
if(foo != null) foo = foo.trim();
if(foo !=null && !foo.isEmpty()){
if(foo.substring(1).equals("bar")){
} else if(foo.substring(4,6).equals("bar")){
}
}
You can also create an utility method for this:
static String safeTrim(String s) {
return s == null ? null : s.trim();
}
And use it:
String foo = safeTrim(getFoo(storedProcedureResult));
Actually such method exists in Apache Commons Lang.
More generic solution would be to convert null string to empty via the special method:
static String nullToEmpty(String s) {
return s == null ? "" : s;
}
And use it like this:
String foo = nullToEmpty(getFoo(storedProcedureResult)).trim();
if(!foo.isEmpty()){
if(foo.substring(1).equals("bar")){
} else if(foo.substring(4,6).equals("bar")){
}
}
Actually such method is available in Google Guava.
Finally you may use Java-8 Optional
if you don't want to create/use non-standard methods:
String foo = Optional.ofNullable(getFoo(storedProcedureResult))
.map(String::trim).orElse("");
if(!foo.isEmpty()){
if(foo.substring(1).equals("bar")){
} else if(foo.substring(4,6).equals("bar")){
}
}