jeudi 6 février 2020

Splitting class responsibilities without exposing too much

I'm having a hard time finding good ways to split class responsibilities without having to expose too much of the original class.

As a simple example I've got this Product class which provides all the operations a product can do, but can also draw itself onto the GUI:

/* Only relevant pieces shown. */
class Product
{
public:

    void
    Draw(QPainter& painter);

private:

    QPointF mPosition;
    Rotation mRotation;
    QColor mFillColor;
    QColor mOutlineColor;
};

I feel this breaks the SRP. The way a Product is to be drawn can change and this has nothing to do with the management of a Product. Or perhaps, later, there might be demand for multiple ways to draw a Product and one wouldn't want to keep modifying the Product class itself for this.

But, off course, as soon as one wants to move the drawing code elsewhere, those private variables will have to be exposed, which also does not sit right with me. I'd be adding a bunch of getters (which feels damn ugly in and off itself) and I'd be tying myself down to maintaining this new "interface" forever. It also collides with the "Tell, don't ask" principle.

Surely there have to be better methods for problems like these ? (examples with C++ code would be nice, in stead of just theorizing).

Aucun commentaire:

Enregistrer un commentaire