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

The single app analytics solutions to take your web and mobile apps to the next level.  Try today!  Brought to you in partnership with CA Technologies

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?

CA App Experience Analytics, a whole new level of visibility. Learn more. Brought to you in partnership with CA Technologies.

Topics:
java ,php ,ruby ,arguments

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}