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!
>Solution :
Either way is allowed. I have seen both used, even within the libraries bundled with Java.
Prefer overloading
👉 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.
Self-documenting code is generally preferable.
By the way, the technical term for adding methods that share a name is overloading.