DEV Community

Philip Perry
Philip Perry

Posted on • Originally published at programming-decoded.com on

Choosing which refactorings to use based on code smells

This week I finished the excellent interactive course Dive Into REFACTORING, which is based on the famous book „Refactoring“ by Martin Fowler. At the end of the course I even received a nice certificate :-

But what is the use of doing a course if one doesn’t know how to apply it to one’s code? The course introduces 66 refactorings which are obviously too many to apply all at once! Originally I was going to title this blog post „My favorite refactorings“, but then I realized that most of them are based on a few code smells, which the course also introduces (21 to be exact).

So my first step was to decide on the worst code smells of the code base I want to refactor.

These are:

– Long method

– Primitive Obsession

– Long Parameter List

– Conditional Complexity

Thankfully the course provides a handy cheat sheet that shows you which refactorings to use for a certain code smell. Based on that, I’ve chosen to concentrate on the following refactorings for the moment:

– Extract Method

– Replace Array with Object

– Decompose Conditional

– Remove assignments to parameters

– Replace method with method object

– Replace Type Code with Class

– Replace Magic Number with Symbolic Constant

– Preserve Whole Object

– Introduce Parameter Object

– Replace Nested Conditional with Guard Clauses

– Introduce Null Object

Of course, there are more than 11 refactoring techniques that are useful, but it’s hard to keep all of them in one’s head and I like to start with small steps. To be honest, a lot of the refactorings should actually be common sense, but when one is time-constrained, one can easily get into bad habits and for instance add another line to a method instead of extracting it.

Doing the course I learned that it’s possible to introduce new, different kinds of code smells while refactoring, so I’ll have to go over the various techniques again at a later point.

Alexander Shvets, the creator of this course recently also published a book called “Dive Into Design Patterns” which I’ve began reading. I like his style of explaining how and why to use various techniques. Using design patterns is the next step in writing more maintainable code.

Top comments (0)