1

When is it bad to make the return type of a method its own class? for example:

class Stuff{
public:
    Stuff &change_name(std::string name) {...} // is this better,
    void   change_name(std::sring name) {...}  // than this?
};

Is it better to make change_x return Stuff or just make it void? because I don't really see a reason why someone will make a sequence of command when calling the method change_name, or is it may be a good practice to always return a supposed to be void method to return its class?

0_NULL
  • 73
  • 1
  • 7
  • If its useful to chain your methods then return `this` otherwise don't – Alan Birtles Nov 28 '20 at 09:39
  • If there are multiple things that the user might want to change then returning a reference allows the user to chain multiple setters, e.g. `x.change_name("john").change_age(33).change_address("...");` This pattern has a name (can't remember what it is however). – john Nov 28 '20 at 09:39

1 Answers1

1

This pattern is useful if you have a class that is meant to change its state repeatedly. Or more succinct, a class that has its main purpose in changing its state by its client code. As in general, you should try to minimize the number of possible states a class instance can be in, use the return *this technique only when its API is clearly superior compared to void member function return types.

The prototypical example here is a builder-class. When you have a complicated constructor of some class to call, with many parameter that depend on several inputs, it can make sense to wrap the construction into a separate builder class. Example client code:

Builder b{/* ... few arguments */ };

b.setName(/* ... */).
  setId(/* ...*).
  setSomeNumber(/* ...*).
  setSomeState(/* ...*).
  setOtherState(/* ...*);

Object thatsWhatIAmInterestedIn = b.construct();

This method chaining is terse compared to the distinct invocation of void member functions, and it will easily be recognized as a builder process.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
lubgr
  • 37,368
  • 3
  • 66
  • 117