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

前端 未结 5 436
感动是毒
感动是毒 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:16

    In my experience, the use of null as a sentinel for the default parameter is more of an idiom in Python. In Java, you can just overload the method.

    void doStuff() {
        doStuff(DEFAULT_VALUE);
    }
    
    void doStuff(final String val) {
        assert (val != null); // or whatever
        ...
    }
    

提交回复
热议问题