J
jstorta
I have question regarding best practices.
Let's say I am writing a method that takes a String parameter and
returns a formatted String.
For this discussion we'll use the following.
String makeUpper( String paramString ) {
return parameterString.toUpperCase();
}
If parameterString is null then the code will return a
NullPointerException. I have two ways to solve this problem.
Use a try/catch block
String makeUpper( String paramString ) {
try {
return parameterString.toUpperCase();
}
catch ( NullPointerException e ) {
return "-";
}
}
OR
Use an if/else condition
String makeUpper( String paramString ) {
if ( paramString != null ) {
return parameterString.toUpperCase();
}
else {
return "-";
}
}
As far as I know both will accomplish the same thing, but I am not sure
which is the best practice for such situations or if it just personal
preference.
If one is better than the other, please set me straight.
Thanks
Let's say I am writing a method that takes a String parameter and
returns a formatted String.
For this discussion we'll use the following.
String makeUpper( String paramString ) {
return parameterString.toUpperCase();
}
If parameterString is null then the code will return a
NullPointerException. I have two ways to solve this problem.
Use a try/catch block
String makeUpper( String paramString ) {
try {
return parameterString.toUpperCase();
}
catch ( NullPointerException e ) {
return "-";
}
}
OR
Use an if/else condition
String makeUpper( String paramString ) {
if ( paramString != null ) {
return parameterString.toUpperCase();
}
else {
return "-";
}
}
As far as I know both will accomplish the same thing, but I am not sure
which is the best practice for such situations or if it just personal
preference.
If one is better than the other, please set me straight.
Thanks