Falling back on default values - better coding practice

时间:2018-09-18 19:40:46

标签: java

When falling back on default values (in the below case name "John Doe"), which code appears better from the readability and possibly performance point of view:

String name;
if(last != null && first != null) {
    name = last + first;
} else {
    name = "John Doe";
}

Or a case without else statement:

String name = "John Doe";
if(last != null && first != null) {
    name = last + first;
}

Does any of the above approaches have any significant drawbacks in your opinion?

1 个答案:

答案 0 :(得分:0)

My personal preference is the second option, because of two reasons:

  • it is shorter - less code to maintain the better
  • definition of a local variable without an assignment is a code smell - it always raises the question "is the current code guaranteeing a value is assigned to this local variable"?

In terms of performance, you need to measure it, but I bet the Java Virtual Machine is able to optimise both of the above approaches and there are no significant differences in execution.