paint-brush
Code smell: side-effects of Deathby@douglascaina
2,563 reads
2,563 reads

Code smell: side-effects of Death

by Douglas CainaOctober 30th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

After some time developing, one thing is for sure, you will always regret the code you did.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail
featured image - Code smell: side-effects of Death
Douglas Caina HackerNoon profile picture

After some time developing, one thing is for sure, you will always regret the code you did.

One of my last regrets came from the side effects, I’m used to sending some object reference to some method and update its content by reference, its something quite common in a daily basis.

With a code like that, its easy to mess things up and keep adding more responsibilities to the side effect, the problem is that your code become a wild horse, you’ll never know where his going. Like this “setPet” method call, it’s seems to be so harmless at first, but imagine it in a code with thousands of lines, a bug in this code would be hell to spot.

Other thing that we can notice in this code is the method signature, it’s a lie! How could we know that he is going to fetch data from some service? And even if we put in the name every little side effect in the signature, it would be more than 200 characters in a glimpse.

But I want to extract this logic from my method so he can be more readable!

I believed in this, extracting methods from my code sending the reference of my class through a long journey of side effects, just to satisfy my ideal of clean code, like the code below:

When you read the only public method “insert()” it seems easy to understand and a pretty straight code, but there’s a lot of black magic around here. Take for example the “populatePersonFamily()” method, it sets the object’s civil state property, but its never declared in anywhere, imagine if the front-end wants to change this value, you’ll have to debug the entire process until you catch this little trick!

Another lesson I took from this is: why should I create a new method to isolate some logic if i’ll never reuse this? don’t take me wrong, I’m not saying to start a method with five hundred lines! It’s all about Design Pattern and Responsibilities.

The Problem with my code was only a misunderstand of the Single Responsibility Programming, why validate the Person object in the service if it’s a front-end rule? Why should a Person service know how to set the Pet object and map the values of a model? All of this is subject for another day but you got the idea.

Side-effect is like a fake friend at school, you think he is helping you until you need his help to resolve some issue. Its hard to trace some bug, its hard to know the impact of a new feature on some method that works with references and its even harder to refactor a method that works this way.