2

In VB / VBA you can do something like this:

With person
    .Name = "John"
    .Age = 32
End With

But in java I can't figure out how or if that functionality exists. Everything I see seems to just repeat the object references, like this:

person.setName("John");
person.setAge("32");

If it doesn't exists, is there at least some methodology to cut down on the repetition?

Sam Hosseini
  • 813
  • 2
  • 9
  • 17
LimaNightHawk
  • 6,613
  • 3
  • 41
  • 60

1 Answers1

3

If it doesn't exists, is there at least some methodology to cut down on the repetition?

Nope, not really - not unless you control the type.

If you do control the type, you can make the set methods return this, allowing you to chain the method calls. This is often useful for builder types:

Person person = Person.newBuilder().setName("John").setAge(32).build();

(You can just make your types mutable rather than separating builder types from immutable non-builder types, but I'm just a fan of immutability...)

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194