Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading