How to solve the violations of the Law of Demeter?

后端 未结 10 1255
一个人的身影
一个人的身影 2021-01-29 22:23

A colleague and I designed a system for our customer, and in our opinion we created a nice clean design. But I\'m having problems with some coupling we\'ve introduced. I could t

10条回答
  •  太阳男子
    2021-01-29 23:00

    Instead of going all the way and providing getters/setters for every member of every contained object, one simpler alteration you can make that offers you some flexibility for future changes is to give objects methods that return their contained objects instead.

    E.g. in C++:

    class Medicine {
    public:
        AdministrationRoute()& getAdministrationRoute() const { return _adminRoute; }
    
    private:
        AdministrationRoute _adminRoute;
    };
    

    Then

    if (Medicine.AdministrationRoute.Soluble) ...
    

    becomes

    if (Medicine.getAdministrationRoute().Soluble) ...
    

    This gives you the flexibility to change getAdministrationRoute() in future to e.g. fetch the AdministrationRoute from a DB table on demand.

提交回复
热议问题