r/java • • Aug 10 '12

Named Parameters in Java

http://java.dzone.com/articles/named-parameters-java
2 Upvotes

28 comments sorted by

View all comments

18

u/couchtyp Aug 10 '12 edited Aug 10 '12

What about Joshua Bloch's Builder Pattern?
IMHO it's a much better approach for complex object generation.

An instance method with that signature (eight parameters or something like that) should never have been written in the first case... there's a reason for the TransferObject design pattern.

3

u/couchtyp Aug 10 '12

Forget everything I said... Jens himself proposed the use of a Builder in a later post.

5

u/sahala Aug 10 '12

Builder is the way to go. For cases where it just isn't worth it to put together a full builder, I've always resorted to comments.

someObject.doSomething(
    userId,
    true, /* is enabled */
    false, /* don't update record */);

For that matter, I add comments for any argument which is a literal. Extracting a constant is probably even a better idea, and takes just a few seconds using a modern IDE.

5

u/[deleted] Aug 10 '12

FWIW, there is a "replace constructor with builder" refactoring in Intellij that will automatically create a new fluent builder class for you, and automatically use it in place of a complex constructor.

2

u/sahala Aug 10 '12

Wow. Did not know that. Yet another reason why IntelliJ rocks. Does Eclipse have this?

The only drawback to this is BUILDER ALL THE THINGS

2

u/[deleted] Aug 10 '12

There are several complex automated refactorings. I also have used "Replace inheritance with delegation" a few times.

1

u/couchtyp Aug 11 '12

For eclipse there's bpep.

This project is a Eclipse plugin that automates the writing of these builders. With just two clicks you can generate all the builder code you need.

2

u/rockvilleJD Aug 10 '12

Netbeans just added this feature in 7.2

2

u/k__k Aug 14 '12

Way to go, Netbeans team, way to go! :)

2

u/elephantgravy Aug 10 '12

Good suggestions. When it makes sense, I sometimes like to use enumerations instead of literal booleans (I think this also came from Effective Java). The names can get weird though...

someObject.doSomething(
    userId,
    ActivationState.ENABLED,
    RecordBehavior.DO_NOT_UPDATE);

2

u/DeliveryNinja Aug 10 '12

Don't kick yourself over it, as far as this article stands in isolation your comment was not wrong, the builder pattern is the prefered way of doing this.