在我的編碼風格中,類不應公開「原始」數據成員,而只能是getter和setter(即使它們是簡單的單行方法)。
這是因爲未來可以升級代碼,單線方法可以擴展到更復雜的東西(或者可以添加一些僅用於調試的構建功能來檢查某些不變量等),所以最好讓客戶端的接口保持一致(如果你暴露「原始」數據成員,這是不可能的)。
您可以避免使用前綴get_()
,只需將該數據成員視爲一個簡單的(不含get_...
)名稱的「屬性」即可。
class Shape
{
public:
....
COLORREF Color() const // Just Color() i.e. the property name, without get_...
{
return m_color;
}
private:
COLORREF m_color;
};
並編寫客戶端代碼,如:
Shape s;
COLORREF someColor = s.Color();
這看起來好像沒什麼問題。
對於您可以像使用語法二傳手:
Shape& Color(COLORREF color)
{
m_color = color;
return *this;
}
,並寫出這樣的客戶端代碼:
Shape s;
s.Color(...).Draw(); // set color and draw shape
如果屬性的類型是東西比COLORREF
更復雜(這是一個32位的DWORD
),你可以使用一個模式,如:
std::wstring Name() const // getter
{
return m_name;
}
Shape& Name(std::wstring name) // setter
{
// Pass by value and move from the value (C++11 move semantics)
m_name = std::move(name);
return *this;
}
但是,當按值返回時,它肯定會創建一個數據結構的副本。如果其中一個嵌套數據結構很大,考慮到我只想讀取一個字段,這不是一個好主意。 – jbgs
@jbgs這取決於它返回的內容。如果它返回一個成員對象,是的,它將不得不復制它。 –
是的,這些嵌套的數據結構是成員對象。實際上我認爲常見的C++編碼風格並不適合我正在開發的這種應用(微電子仿真)。 – jbgs