简体   繁体   中英

Is it okay to pass null/empty unused parameters to a method?

I'm trying to find what is the best practice to do in a similar case, say I have a method

String getContent(String id, Boolean remove_tags) {
    …
}

This has a long implementation, and I need the functionality but in some cases I don't want to send the second parameter, is the right practice for this case to pass it as null or to create a another method with only the first parameter and make that method return this one this way:

String getContent(String id) {
     return getContent(id, null);
}

I've read a suggestion in this question [here][1] to only pass it as a null.

I might be making a big deal of nothing , but I've tried to make a couple researches about such a topic and couldn't find something useful, so I need some opinions please about this!

[1]: https://stackoverflow.com/questions/21205492/how-do-you-call-a-method-using-only-some-of-its-parameters#:~:text=You%20can%20pass,null%2C%20null%2C%20null )%3B

Either way is allowed. I have seen both used, even within the libraries bundled with Java.

Adding the second method with a single parameter has the benefit of clearly communicating that a single argument will succeed.

With only the first method, the calling programmer cannot tell if passing a null for the second argument is allowed. She would have to study the Javadoc or perhaps even the source code to determine if a null will succeed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM