Search code examples
c++ooprefactoringlaw-of-demeter

How to restructure this code hierarchy (relating to the Law of Demeter)


I've got a game engine where I'm splitting off the physics simulation from the game object functionality. So I've got a pure virtual class for a physical body

class Body

from which I'll be deriving various implementations of a physics simulation. My game object class then looks like

class GameObject {
public:
   // ...
private:
   Body *m_pBody;
};

and I can plug in whatever implementation I need for that particular game. But I may need access to all of the Body functions when I've only got a GameObject. So I've found myself writing tons of things like

Vector GameObject::GetPosition() const { return m_pBody->GetPosition(); }

I'm tempted to scratch all of them and just do stuff like

pObject->GetBody()->GetPosition();

but this seems wrong (i.e. violates the Law of Demeter). Plus, it simply pushes the verbosity from the implementation to the usage. So I'm looking for a different way of doing this.


Solution

  • The idea of the law of Demeter is that your GameObject isn't supposed to have functions like GetPosition(). Instead it's supposed to have MoveForward(int) or TurnLeft() functions that may call GetPosition() (along with other functions) internally. Essentially they translate one interface into another.

    If your logic requires a GetPosition() function, then it makes sense turn that into an interface a la Ates Goral. Otherwise you'll need to rethink why you're grabbing so deeply into an object to call methods on its subobjects.