Large scale usage of Meyer's advice to prefer Non-member,non-friend functions?

后端 未结 8 1081
無奈伤痛
無奈伤痛 2021-02-05 00:15

For some time I\'ve been designing my class interfaces to be minimal, preferring namespace-wrapped non-member functions over member functions. Essentially following Scott Meyer

8条回答
  •  清歌不尽
    2021-02-05 01:12

    I'd argue that the benefit of non-member functions increases as the size of the project increases. The standard library containers, iterators, and algorithms library are proof of this.

    If you can decouple algorithms from data structures (or, to phrase it another way, if you can decouple what you do with objects from how their internal state is manipulated), you can decrease coupling between your classes and take greater advantage of generic code.

    Scott Meyers isn't the only author who has argued in favor of this principle; Herb Sutter has too, especially in Monoliths Unstrung, which ends with the guideline:

    Where possible, prefer writing functions as nonmember nonfriends.

    I think one of the best examples of an unneccessary member function from that article is std::basic_string::find; there is no reason for it to exist, really, as std::find provides exactly the same functionality.

提交回复
热议问题