Non-member non-friend functions vs private functions

前端 未结 4 938
情歌与酒
情歌与酒 2020-12-31 06:42

Herb Sutter has said that the most object oriented way to write methods in C++ is using non-member non-friend functions. Should that mean that I should take private methods

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-31 07:17

    This question appears to have already been addressed in answering a different question.

    Such rules tend to be good servants and bad masters, there are trades-off involved. Is the result more maintainble if you apply the transformation you suggest? Why? I believe that the intended benefit is that by reducing the number of methods directly dealing with the private data of the object you can more easily understand its behaviour and hence make it easier to maintain.

    I don't believe that your after example achieves this goal. [You may notice that the "after" example above won't compile anyway, but that's another story.] If we adjust it to implement the external functions purely in terms of public methods rather than internal state (add an accessor for the value) then I guess we've had some gain. Is it enough to warrant the work. My opinion: no. I think that the benefits of the proposed move to external function become much greater when the methods update the data values in the object. I would want to implement a small number of invarient-maintaining mutators and implement the major "business" methods in terms of those - externalising those methods is a way of ensuring that they can only work in terms of mutators.

提交回复
热议问题