This article is one of <Effective C++> reading notes.
Part 4: Designs and Declarations
Item 23: Prefer non-member non-friend functions to member functions.
Things To Remember
- Prefer non-member non-friend function. Doing so increases encapsulation, packaging flexibility, and functional extensibility.
Key Points
Increases encapsulation:
- It affords us the flexibility to change things tin a way that affects only a limited member of clients. The less code that can see the data (i.e., access it), the more the data is encapsulated.
- Non-member non-friend function doesn’t increase the number of functions than can access the private parts of the class.
- Module interfaces should be streamlined as much as possible.
- Two things are worth noting: 1.) this reasoning applies only to non-member non-friend functions. 2.) a function be a non-member of one class doesn’t mean it can’t be a member of another class.
A more natural approach would be to make clearBrowser a nonmember function in the same namespace as WebBrowser.
Increases packaging flexibility (包装弹性):This is exactly how the standard C++ library is organized. Rather than having a single monolithic <C++StandardLibrary> header containing everything in the std namespace, there are dozens of headers (e.g., <vector>, <algorithm>, <member>, etc.), each declaring some of the functionality in std.
Increases functional extensibility (功能扩展性):Putting all convenience functions in multiple header files — but one namespace — also means that clients can easily extend the set of convenience functions. All they have to do is add more non-member non-friend functions to the namespace.
- Clients can drive new classes to extend the old one, but derived classes have no access to encapsulated (i.e., private) members in the base class.
Code
|
|