Duplication vs Coincidence

In order to be able to serialize all of the properties on our Book And Author entities we are going to use an interface called JsonSerializable which mandates a method called jsonSerialize.

We use the jsonSerialize method to tell PHP which of the properties to serialize. In our case we want to serialize all of the properties on both the Book and the Author so we can simply return an array of all of the objects variables.

This means, however, that the jsonSerialize method will be exactly the same for both classes.

Is this duplication? Actually, no it is not...it is a coincidence. Just because we are serializing all properties right now, that does not make it the rule and there may be a time when one of the objects has properties that should not be serialized. So we should not treat this a duplication.

Many new (and some not-so-new) developers fret about duplication when they see two pieces of code that look the same and immediately start to refactor, often ended up with more code to maintain than if they hadn't.

The important question to ask is 'if I change the code in one place, do I need to change it in the other?' (which here we don't). If the answer is yes, you have duplication BUT it is still not essential to refactor straight away, especially if it is only a small amount of code. Relax 🏝

Branch: https://github.com/GaryClarke/pest-tdd/tree/41-duplication-vs-coincidence

Complete and Continue  
Discussion

0 comments