2

I'm using C++ and Java for a while and recently I'm on jquery. I noticed jquery's chain style functions. Then I think, if we could change setters in C++/Java just like jquery? For example, if our code is

class Person {
    private String name;
    private int age;

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }

    public Person setName(String name) {
        this.name = name;
        return this;
    }

    public Person setAge(int age) {
        this.age = age;
        return this;
    }
}

Then we could write code as following instead:

Person person = new Person();
person.setName("Tom").setAge(20);

If we have lots of setters, this seems to be more simple.

I wonder if this is a good idea? Do you agree with me? Just give me your opinion. Thank you!

devbean
  • 95
  • 1
  • 6
  • There's nothing wrong with this approach, and some built-in utilities use this pattern (`StringBuilder`, for instance). Personally I don't like it, but that's just me. If it works for you, then go for it. – aroth Mar 19 '12 at 02:46
  • Related: http://stackoverflow.com/q/4899756/240633 – ergosys Mar 19 '12 at 02:51
  • 1
    You would have to return a reference if you want the different setters to modify the same object, or else store the object somewhere at the end of the chain of setters. – David Rodríguez - dribeas Mar 19 '12 at 02:58

3 Answers3

5

This is generally used to create a fluent interface and can be implemented in any language.

  • Pros: can improve readability and allows for more concise code.
  • Cons: debugging may be harder as breakpoints are usually line-based.
JRL
  • 76,767
  • 18
  • 98
  • 146
4

This is typically called as Method Chaining in C++.
Using Method Chaining is more a question of choice.

The most common use of method chaining is in the iostream library.
E.g., cout << x << y works because cout << x is a function that returns cout.

Method chaning is typically used in Named Parameter Idiom.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

Method chaining works fine in C++, and doing it is no problem at all.

Using getters/setters (aka accessors and mutators) enough to care about chaining them hints that your code has design problems though.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111