mardi 9 novembre 2021

Solution to enforce invariant for object state

I have a problem that probably has some standard solution or a design pattern that I'm unaware of. Suppose I have a Rectangle class like this:

class Rectangle {
public:
    void setShape(float top, float left, float width, float height);
    void setCenter(float cx, float cy);
private:
    float top, left, width, height, center_x, center_y;
}

Now, when a user of Rectangle calls setShape, the method will also set the center and if the user calls setCenter, the method will modify top and left accordingly, such that the center of the rectangle is consistent with it's top-left corner.

However, in a more complicated setting, it is easy to introduce a bug by setting the relevant fields in a setter and not modifying the remaining fields such that the entire object remains consistent and makes sense.

Is there a general solution / design pattern to somehow enforce, either at compile time or at runtime, that an object will satisfy some invariant after each setter is finished?

Thanks

Aucun commentaire:

Enregistrer un commentaire