The Law of Demeter
15/Feb 2009
I’ve been refactoring big pieces of legacy code recently and my work would be much easier if authors would have followed the Law of Demeter. It’s not even LoD per-se, it’s mutated version, because I’m not talking about calling methods, rather accessing fields. The general guideline is – where possible, function should only operate on a minimal required subset of data. Consider the following code snippet:
float GetDistanceFromCamera(const Object& obj, const Camera& camera)
{
return (obj.GetPosition() - camera.GetPosition()).Length();
}
float GetDistanceFromCamera(const Vec3& objPos, const Vec3& camPos)
{
return (objPos - camPos).Length();
}
float GetDistanceBetweenPoints(const Vec3& p1, const Vec3& p2)
Old comments
Paul Evans 2009-02-15 19:12:11
I don’t think it is that artificial because I have seen code very much like your first example.
Nice article.
getposition 2010-04-03 10:28:35
[…] … Unfortunately at the moment the getPosition command for the Primitive Object is broken. …The Law of Demeter | .mischief.mayhem.soap.I've been refactoring big pieces of legacy code recently and my work would be much easier if authors […]