Borrowing Language Features: Default Argument Values in Java
In PHP, I've come to really enjoy being able to add another argument to a method and give it a default value. Now we'll apply it to Java.
Join the DZone community and get the full member experience.
Join For FreeI've been doing a lot of coding in other languages lately, primarily PHP with some Ruby thrown in there, in addition to my regular Java coding and there's one feature that I've been missing from my Java code...
In PHP, I've come to really enjoy being able to add another argument to a method and give it a default value, instantly providing backwards compatibility without needing to add another method that calls yet another method with a default value. Take the following two snippets of code for example:
Java:
public void methodA(String arg1, String arg2) { methodA(arg1, arg2, "default");}public void methodA(String arg1, String arg2, String arg3) { // Do something to the arguments there}
PHP:
function funcA($arg1, $arg2, $arg3 = 'default') { // Do more here}
In our last Javalobby Newsletter, the author argued that Lines of Code is a bad argument, and I tend to agree. My reasoning here isn't because I'm lazy and don't like more lines of code. My argument is that the PHP option is easier to maintain, given that there is only one function. Given Java's speed, what does a function call cost? Is it more expensive to call 2 methods than just a single one?
I'm not saying that this style is for everyone, but I know I would benefit from it. I've seen my share of weirdness from PHP lately, and it has made me appreciate Java and the speed and stability of a Java server more than I ever did before (for example, I never thought that a Java app server was light on memory use :)). Other languages often have nice things we can borrow from them, and I think that this is one of them. What do you think?
Opinions expressed by DZone contributors are their own.
Comments