Effective-cpp-#23

Prefer non-member non-friend functions to member function

动机

考虑两种程序组织方式:

1
2
3
4
5
6
7
8
9
10
11
12
13
class WebBrowser {
public:
...
void clearCache();
void clearHistory();
void removeCookies();
...
void clearEverything(){
this.clearCache();
this.clearHistory();
this.removeCookies();
}
};
用一个非成员函数去封装
1
2
3
4
5
void clearBrowser(WebBrowser& wb){
wb.clearCache();
wb.clearHistory();
wb.removeCookies();
}

到底选择哪一种好呢?我们先从封装开始考虑起,越多东西被封装,就意味着越少人可以看到它,那么就会有更大的弹性去改变它。 通常来说,越多函数可以访问它,就意味着数据的封装性越低。



解决方法

因此通常来说,如果有两个程序组织方式————member函数和non-member函数两种,而它们的机能相同,那我们应该选择封装性更大的non-member函数,因为它们不会增加"能够访问"class内的private成分的函数数量


另外,尽管我们将使用non-member函数,但这并不意味着该函数不能成为其它类的一部分,例如,我们可以另void clearBrowser()其成为某些工具类的static member函数

通常来说,在C++中比较自然的做法是将non-member函数与类放在同一个namespace中:

1
2
3
4
namespace WebBrowserStuff{
class WebBrowser {...};
void clearBrowser(WebBroser& wb);
}

建议

  • 宁可拿non-member non-friend 函数来替换member函数。这样做可以增加封装性,package flexibility和机能扩充性。