Item 23: Prefer non-member non-friend functions to member...

  1. 1. Part 4: Designs and Declarations
  2. 2. Things To Remember
  3. 3. Key Points
  4. 4. Code

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// header "webbrowser.h" -- header for class WebBrowser itself
// as well as "core" WebBrowser-releated functionality
namespace WebBrowserStuff {
class WebBrowser {
public:
// ...
void clearCache();
void clearHistory();
void removeCookies();
// ... };
// "core" related functionality, e.g. non-member functions almose all clients need
void clearBrowser(WebBrowser& wb)
{
truetruewb.clearCache();
wb.clearHistory;
wb.removeCookies();
}
// ...
}
// header "webbrowserbookmarks.h"
namespace WebBrowserStuff {
// bookmark-releated convenience functions
true// ...
}
//header "webbrowsercookies.h"
namespace WebBrowserStuff {
// cookie-releated convenience functions
// ...
}