C++核心準則C.131: 避免無意義的getters和setters


C++核心準則C.131: 避免無意義的getters和setters

C.131: Avoid trivial getters and setters

C.131: 避免無意義的getters和setters

Reason(原因)

A trivial getter or setter adds no semantic value; the data item could just as well be public.

無意義的getter和setter不會增加任何語義上的價值,數據項只要定義為public就好。

Example(示例)

<code>class Point {  // Bad: verbose  int x;  int y;public:  Point(int xx, int yy) : x{xx}, y{yy} { }  int get_x() const { return x; }  void set_x(int xx) { x = xx; }  int get_y() const { return y; }  void set_y(int yy) { y = yy; }  // no behavioral member functions};/<code>

Consider making such a class a struct -- that is, a behaviorless bunch of variables, all public data and no member functions.

考慮將這樣的類定義為struct--也就是說,不包含行為的數據群,所有數據都公開,沒有成員函數。

<code>struct Point {  int x {0};  int y {0};};/<code>

Note that we can put default initializers on member variables: C.49: Prefer initialization to assignment in constructors.

注意我們可以為成員變量設置初始化器:C.49:初始化比在構造函數中複製更好。

Note(注意)

The key to this rule is whether the semantics of the getter/setter are trivial. While it is not a complete definition of "trivial", consider whether there would be any difference beyond syntax if the getter/setter was a public data member instead. Examples of non-trivial semantics would be: maintaining a class invariant or converting between an internal type and an interface type.

這條準則的關鍵是getter/setter的語義是不是有意義。如果不能完全定義“無意義”,考慮如果getter/setter如果是公有成員的話是否存在任何的不同。有意義的語義的示例:維持類的不變量或者在內部數據類型和接口數據類型之間進行轉換。

Enforcement(實施建議)

Flag multiple get and set member functions that simply access a member without additional semantics.

如果存在多個get和set成員函數只是簡單地訪問數據成員卻不包含附加意義,進行提示。

原文鏈接:

https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#c130-for-making-deep-copies-of-polymorphic-classes-prefer-a-virtual-clone-function-instead-of-copy-constructionassignment​


覺得本文有幫助?請分享給更多人。

面向對象開發,面向對象思考!


分享到:


相關文章: