A useful rule-of-thumb for Law of Demeter violations?

I’m in a QA testing cycle on my current project, so I have a few minutes here and there to look at things I’ve put aside during busy times. Right now I’m finally reading through Writing Testable Code by the Google people. It’s good, if a little Google-centric (lots of references to Guice as a good way to fix the flaws they point out).

It’s paid off. I found this gem regarding Law of Demeter violations:

You should never have to mock out a setter or getter.

Wow. Simple enough to always keep in mind, and very easy to look for as a code-smell. Plus, it’s test-driven in focus, which I’ve always found to be the best way to shake out good architecture/development ideas.

I’m going to need to mull this over a bit, looking for the sharp corners. For example, in my current contract, there is a lot of legacy code, and I’m wondering how often I’ve mocked getters because I wasn’t able to cut through the Gordian knot of interdependency in that codebase.

I’m definitely going to give this sort of acid-test a shot in my development, though. It feels very useful and very communicable to those who are having trouble grokking the whole of test-driven development.

Leave a Reply

Your email address will not be published. Required fields are marked *