If the exception occurs I need to cut the resulting String by a value obtained in another method.
I have a resulting method :
private String generateSomeName() {
String basicProjectName = "Sth_" + method1();
return basicProjectName + "_" + "X" ;
}
private String method1() {
try {
Class.getNumber(); //returns String1
} catch (Exception e) {
log.warn("Unable to get this Number", e);
}
return "";
}
My problem is that when everything works I will get the proper format of the String Sth_String1_X
But if there is an exception and I will get the empty String "" (without String1) my result is:
Sth__X
(with double _)
And I need it to be:
Sth_X
with only one _
Any tips how to handle this?
Assuming java 8 is used, an option would be to use Optional
to add the _
before the result returned by the method1
method only if the result is not null and non empty
private String generateSomeName() {
String basicProjectName = "Sth" + Optional.ofNullable(method1())
.filter(s -> s.length() > 0)
.map(s -> "_" + s)
.orElse("");
return basicProjectName + "_X" ;
}
private String method1() {
try {
Class.getNumber(); //returns String1
} catch (Exception e) {
log.warn("Unable to get this Number", e);
}
return "";
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments