Last weekend I was at SoCraTes Canaries and I gave my first talk ever about code smells. Oh boy! How nervous was I! But now that has passed, I was wondering what I should do with all information I gathered. And then I thought, maybe it's a good idea to put it all in a nice blog post.
A code smell is a surface indication that usually corresponds to a deeper problem in the system.
I like to think that a code smell is something that makes your developer instinct cry out to you, and you just know that something is wrong. This doesn’t mean you have to make changes in your code: there are occasions where these code smells are ok, but I think it’s important for us to detect them and know exactly why they are there.
There are five categories of code smells:
Today I'm going to talk about Bloaters. I'll leave the other categories for a future post.
Bloaters can be big methods or classes, primitive obsessions, data clumps, or long parameter lists.
Long Parameter List/Data Clumps
The Long Parameter List is when you have a method that has more than 3 parameters. Sometimes we see that when we receive an object, and instead of passing it all we pass some of its data. In this case, the best policy is to pass the whole object. Data Clumps are a bit different: they are, in general, primitive values that start to "get together". A good example of this is a startDate and endDate... Maybe it's worth creating a DateRange.
This case is when we use primitives instead of value types for simple tasks. Sometimes the use of primitives is justifiable, but when you start to have behaviour attached to this primitives, then it's time to stop and think that maybe a value type is in order. A simple example is a currency: we tend to put it in a float or double, instead of encapsulating it in a value type.
Long Method / Large Class
This kind of code smell happens when you have a big method. But when do you know that a method has become too big? Well, I have the rule that with more than five lines, you should, at least, look at it again. But, as Sandro told me before, the right number of lines is just enough lines so a method only does one thing (and so it conforms to the 1st principle of SOLID the Single responsibility principle.
To do this blog I started to look at my old code when I hadn't woken up yet to craftsmanship: if it was working that was good enough for me. Here's the code in Objective-C:
Wow! This is a really big method. And it is inside a ViewController class, so this should definitely be extracted into a service class, so we have a correct separation of concerns. But for the sake of the brevity, let's focus on how can we refactor this big method. The refactoring technique to apply here is Extract Method: you can aggregate code together and extract to a new method. So let's see what we can come up with:
We can start with grouping the code that refers to serializing a post: