Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Borrowing Language Features: Default Argument Values in Java

DZone's Guide to

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.

· Java Zone
Free Resource

Get the Edge with a Professional Java IDE. 30-day free trial.

I'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?

Get the Java IDE that understands code & makes developing enjoyable. Level up your code with IntelliJ IDEA. Download the free trial.

Topics:
java ,php ,ruby ,arguments

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}