Should I pre-initialize a variable that is overwritten in multiple branches?

Michu93 :

There is a method:

private String myMethod(String gender)
{
    String newString = "";
    if(gender.equals("a"))
        newString = internal.getValue();
    else
        newString = external.getValue();

    return newString;
}

I refactored everything, but with one small change: String newString; instead of: String newString = "";

Does this refactor improve the code? I know that String is null when we don't initialize it, but in this example it always will have value a from if or else. Does this refactor change anything?

Rogue :

To answer the direct question: there's no need to assign a value initially here; all branches of the code's execution will pan out to giving newString a value. Thus you don't need to initialize it at all. Otherwise, I would initialize to whatever you would want as a "default" value.

Instead of two returns or a branching statement to assign a variable, I would just return with a ternary:

private String myMethod(String gender) {
    return gender.equals("a")
            ? internal.getValue()
            : external.getValue();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=163432&siteId=1