@since Tuesday, January 4, 2011

Don't DRY when YAGNI


No, this is not a post to not follow DRY guidelines, but don't overdo it and damage code readability. 

DRY (Don't Repeat Yourself) guidelines state extracting method, members, classes, etc. to a shared resource so you won't repeat a common logic for any of your operations. If you're practicing an Object Oriented Programming, you're probably saying - DAH!
One of the worst illness of the development world is copy-paste. There are numerous tools to check for code duplications (CPD), but sometimes they're are just causing developers to "fix" code simply to eliminate a CPD potential warning. Some other developers might extract a logic to another class just so "some day in the future someone might need it" (hmmm, YAGNI?). I've seen a piece of code, written by an experienced programmer that instead of calling 4 setter methods, he extracted the code to another class, used reflection to build call sequence and even went the extra mile and created an amazingly complex unit test to ensure those 4 methods are called.
The code described above was rejected for readability. DRY or not DRY, I prefer reading a method and immediately understand what it's doing.


No comments: