DEV Community

Discussion on: When Code Duplication is the Right Answer w/ Sandi Metz

Collapse
 
eudes_40 profile image
eudes

This talk is a masterful walkthrough on how to translate a functional definition into good, extensible code. I found the bit about identifying the GildedRose class as a Factory particularly enlightening.

Not quite sure where the DRY/duplication dicotomy comes into place here, though. I think that transforming a flawed, confusing method into classes that inherit a single API should not be regarded as "repeating yourself". In python you may be tempted to think of it as so, as you have to add lines of code that look the same. But in fact you are just implementing a contract, and for that there's a few things that must be repeated.

This is one of the things that Java does well: in Java you would create an Item interface, and define the different classes that implement it. An interface just defines a contract, a type, with the signature of the methods the subtypes will have. You then must implement each and every method in each of the subclasses. But it doesn't feel as code duplicaton, as the compiler will fail if you don't implement these methods, thus "hiding away" the repeated parts from the things you feel guilty about in your code, as they are not your responsibility.

This brings to mind that thing you hear in talks all the time: patterns are the solutions you use when the language doesn't have the right tool for the problem at hand. I know python has inheritance and types and all the flying colors. But I don't think it is helping the developer get to a good solution if it makes them think that inheritance and contracts are code duplication.