开发者

Getters & Setters in C++

I've been writing a simple program, and I've designed a simple text abstraction - location on the screen X/Y, size of the box X/Y, the text within, and alignment.

But now I have this abstraction which is just a bunch of getters and setters. Normally I would just make this stuff public data members, but the trouble is that I can't just chuck in data members, because in the future, there is an alternative code path in which they don't exist in my code, but in an external library. Now I have a horrendously clunky interface of get/set (improved somewhat by a method chain). What can I do to make it cleaner?

Edit: My class definition.

class Text {
public:
    enum TextLayout {
        TopLeft,
        TopRight,
        BottomLeft,
        BottomRight,
        Center
    };
    // Text
    virtual string GetText() = 0;
    virtual Text* SetText(const string& ref) = 0;
    virtual Text* SetText(string&& ref) = 0;

    // Position
    virtual int GetPositionX() = 0;
    virtual Text* SetPositionX(int x) = 0;
    virtual int GetPositionY() = 0;
    virtual Text* SetPositionY(int y) = 0;
    virtual int GetSizeX() = 0;
    virtual Text* SetSizeX(int sizex) = 0;
    virtual int GetSizeY() = 0;
    virtual Text* SetSizeY(int sizey) = 0;
    virtual TextLayout GetTe开发者_运维技巧xtLayout() = 0;
    virtual Text* SetTextLayout(TextLayout layout) = 0;

    virtual std::shared_ptr<Font> GetFont() = 0;
    virtual Text* SetFont(const std::shared_ptr<Font>&) = 0;
    virtual Text* SetFont(std::shared_ptr<Font>&&) = 0;

    virtual Text* SetColour(unsigned int colour) = 0;
    virtual unsigned int GetColour() = 0;

    virtual Render* GetRender() = 0;

    virtual ~Text();
};


You should encapsulate each concept precisely. cf. Single Responsibility Principle

I think: There should be a class Position, and your class have a position member. There should be a class Size, and your class have a size member. Then you have 4 functions less. And a cleaner encapsulation.

EDIT: removed my comment about passing arguments by references instead of return by copy


I can not see anything wrong with your code. However, you could probably split it to several interfaces, for example IPositionable(x,y), IResizable(width,height), IAlignable(...) Then make some super interface ITextField that extends IPositionable, IResizable and IAlignable. But if you are not going to use that smaller interfaces anywhere else - it is just an overkill. That's a basic idea, but I usually split interfaces to the smallest logical groups of bits.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜