The parameter 'foo' should not be assigned — what's the harm?

前端 未结 5 458
感动是毒
感动是毒 2020-12-17 08:52

Compare this method:

void doStuff(String val) {
    if (val == null) {
        val = DEFAULT_VALUE;
    }

    // lots of complex processing on val
}
         


        
5条回答
  •  难免孤独
    2020-12-17 09:11

    It's sometimes considered a bad practice to reassign parameters inside method. It, probably, comes from C/C++, where calling doSomething(myVar) can change myVar after method is completed. But that's not the case for Java.

    IMHO, if you do it as first thing in the method, this is perfectly fine. Everybody reading your code will understand what's going on. It can be confusing if buried deep in the code, though.

提交回复
热议问题