» Coding

Archive of ‘Coding’ category

Refactoring: A quick overview

Hi! As promised, here I am again with another “basic concepts for coding lovers” thing. Before proceeding, I’d like to say thank you to all the people that read my last post and gave me feedback, because you help me very much during my learning process. :)

Well, after this short but certainly emotive declaration, we’re getting into the matter. Today we’ll learn about refactor. The knowledge for this post proceeds from this book, this site and this site, then I applied my own experience to filter relevant data and make a very basic and summarized guide. Don’t expect to find here all the code smells or refactor techniques that exist, because it is not the purpose of this post.

If you really want to learn how to refactor, you should absolutely read “Refactoring: Improving the Design of Existing Code”, by Martin Fowler (and follow him everywhere). Also I’d like to make some altruistic advertising for these guys, who are regularly making courses and dojos to spread the word of divinity code, amen.


Why to refactor

“If it ain’t broke, don’t fix it”. The program may not be broken, but it does hurt. (M.F.)

I’ve heard this words so many times, and they’ve always upset me. I think they’re the most irritating words along with “It has always been done this way”. So what.

When a code is dirty, it becomes a nightmare for all the programmers working with it, because it is difficult to understand, adverse to changes, and hides bugs like hell.

Clean code, instead, is made to be read by humans and to help them doing their work, either applying changes or finding bugs. A good code is also reusable.

Refactoring is like arranging a chaotic garage. Imagine it, so full of paint buckets, broken toys and scrap, that you can’t even park your car in it. So you roll up your sleeves and start hanging the tools on the wall and getting rid of unused stuff until everything is clean and tidy.

Now you can use your garage and the objects that are on it, you can quickly find the hammer in the wall and the hose in the storage boxes. Besides, you got empty space to add new features, like parking a car or setting up a worbench. You even recovered forgotten toys so you won’t need to buy new ones for your kids.

And most important, now everyone, including you, loves that garage and enjoys working on it, and will probably make an effort to keep it clean because a rag thrown in the middle of your tidy garage would be immediately spotted.

So yeah, a chaotic garage may still be working as a garage, but eveyone prefers your zen garage.


There are some tips to apply when refactoring.

Code must work

First of all, code must work correctly before starting the process. Otherwise you won’t know if a failure is due to a known bug or it is a side effect of your refactor.

First refactor, then add

This rule is explained by the metaphor of two hats, by Kent Beck:

Whenever you are programming, you can wear one of these two hats:
The add hat allows you to add new functionalities and to write tests.
The refactoring hat is dedicated to restructure the code and run the tests.


You can only wear one hat at a time, and you should always be conscious of what hat you are wearing at the moment. Meaning, do not start refactoring if you have not finished adding new logic, and do not stop refactoring whenever you think of a new feature. Just write it down and finish the refactor, then come back to it.

Be always supported by tests

You should create a test suite with which you feel enought comfortable and confident to proceed with a refactor. The tests must be written while wearing the add hat, and ideally generated with TDD, which is a design technique I would like to write about in the future. (Meanwhile you can read this).

Your tests must cover all the parts of the code that will be affected (and potentially broken) by your refactor, either directly or collaterally. Once you have them, start the refactor and throw all the tests each time you take a step. This way you monitor the changes on the code and immediately know if your last change broke your code or not.

Baby steps

Don’t make huge changes at once. Try to go little by little, making steps as small as possible, and always throwing tests after each step. This will minimize the area affected by your last change and it will become easier for you to spot the bug in case tests fail.

This does not mean that you can’t make big changes to your code. It means that big changes must be splitted into small changes and be regularly tested during the refactoring process.


Bad smells

If it stinks, change it (M. F.)

Code smells are symptoms that makes us suspect that our code needs a refactor treatment. So what we’re about to do is learn how to recognize code smells, and later we will speak about how to deal with them.

Speaking with a colleague recently, I was asked if a code smell is a “problem” on the code. Well, I wouldn’t say it is exactly a problem, but more like a warning. Sometimes we even introduce them on purpose to highlight something. So don’t start mass killing bad smells: you have to be reflexive and proceed wisely.

Long method / Large class

A very long method or a large class is probably taking  way more responsibilities than it should, but the worst thing about them is that they are completely unmanageable.

There are several opinions about how long should a method be  to be considered “too long”. Usually, 10 lines or the space that you can see in your IDE without scrolling.

For classes, it’s hard to say. Probably that file with 500 lines of code is stinking like a rotten fish.

No shortcuts: The best way to know if a method or a class is too big, is to inspect it and determine if it is rightly in charge of all those functions. After doing this, check the code itself, because it may contain several smells that are making it so long, like duplicated or unused code.

Data clumps

Those are groups of fields that are related and dedicated to the same function. You’d possibly recognize them because of their names:

This set of fields is obviously dedicated to manage the race of the kitten.

Sometimes you could find data clumps preceded by comments or separated somehow from the rest of the code, which should make your spider sense tingle:


Switch statements

Not only switches, also eternal if/elses and similar structures are considered smells, because this is not how object-orientation works. We’ll see an example later.

Refused bequest

This happens when a subclass does not use all the methods inherited from its father. It is a symptom of that either the class is incorrectly being considered a subtype of that superclass, or the superclass is hanging methods that would better belong to another interface:


Shotgun surgery

When making a single change requires that you perform many small changes to many different classes. This could mean that your classes are coupled to each other.



A code that needs a lot of explanatory comments is therefore an incomprehensible code. And, as we said before, the code must be written for human readers. Ideally, it should be read as prose.  So instead of:

Prefer this:

Zero comments, 100% understandable.

Duplicated code

If you need a functionality again, reuse it. Please stop copypasting.

Sometimes you may duplicate code on purpose because you are not sure where should that code be encapsulated, or because you really don’t know how will it look like when you finish the feature. In that case, wait until it is repeated three times, then start considering encapsulation. This technique is know as The Rule of Three.

Lazy class, dead code and speculative generality

Different names to call the same thing: unused code. If a piece of code is not enought meaningful or you are not using it or you don’t need it right now, get rid of it.

Don’t write code for future eventualities, like “yeah, well, let me create this interface called Poisonous just in case someday I want to add snakes to my game ’cause ya know”.

As my C teacher used to say, “good programmers are lazy programmers”.

Feature envy

When a method or class is continously accessing the data of another object, it would probably be happier having that data within it.

Middle man

A class whose only purpose consists in delegating to another class:

This class has no reason for existence.


Ok, so now that we’re done with code smells, it’s time to get into refactorings. I must warn you that refactoring is not an exact science. Each scene needs a personalized analysis and specific treatment. So I’m providing the tools, but yours is the duty of guessing which tool suits better your situation.

Extract method

Replace a piece of code by a method call:

This is useful not only to lighten up the code, but also to make it more meaningful, because if you gave a good name to the extracted method, you know what’s going on there just reading its call.

There’s a similar result when using extract variable.

Then, in the line of extract variable, we have Replace magic number with symbolic constant, which is used to hide a hardcoded number behind a constant that has a self-explanatory name:

Decompose conditional

This technique consists in replacing complex conditionals into understandable method calls, like this:


Extract class

Although the procedure is similar to extract method, there is an extra benefit, because this refactor allows you to disengage a functionality from a class that was not responsible of it.

Extract superclass / interface

Create shared superclasses and interfaces for classes that have common fields and methods.

Replace method with method object

When it is not possible to extract method because you have plenty of local variables that are mixed together, extract the method to a class and transform these vars to fields:

Move method

Move method and move field consist in moving a method or a field from one class to another. This could be a solution for feature envies.

Hide delegate / Remove middle man

If we take back our example:

MiddleCat is hiding kitten’s methods, meaning, a client that uses this class will never know about Kitten‘s methods because it will be forced to access them through MiddleCat.

This technique, called hide delegate, is useful and used in other cases, but not in this one.

Remove middle man deletes the pointless intermediate class, exposing the final methods directly to the client. In this example MiddleCat is beseeching to die, so we should apply Remove middle man for mercy.

Encapsulate field

Convert a public field to private and provide public methods to work with it.

The most interesting example of this refactor happens when we are working with collections, because it is kind of reckless allowing everyone to play with such a delicate data structure. So instead of exposing it, make it private and create methods for specific operations:

This way you have better control over how your collections (and all kind of fields) are used from the outside.

Hide method

Convert a public method to private or protected.

When programming a new class, I use to set the minimum visibility to its methods, and then relax this as external objects needs to access them. This way I make sure that there’s no indecorous access to my shy resources.

Consolidate conditional expression

Both consolidatre conditional expression and consolidate duplicated conditional fragments are reoganization of conditionals.

If several conditionals lead to the same result, unify them and write the result only once:

If all the conditionals share the same code, move it outside the conditional so everyone can reuse it without duplication:

Replace conditional with polymorphism

This is my favourite one. Imagine you have a conditional such as:

The main problem of this structure is that you will have to add cases each time you want to implement the caress for an animal, and as the game grows, this piece of code will become unmaintainable.

Polymorphism consist in creating classes with common interfaces, and delegating in these classes the responsibility of implementation. So for the example above, we first create classes for each branch of the switch, and a shared interface:

And then we replace the whole conditional by a method call:

IMG_20160814_203449Lovely, elegant and fluffy as a stuffed kitten.

Pull ups and push downs

We say pull up when a field, a method or a constructor is moved from a subclass to a superclass, and push up when a field or a method is moved back from a superclass to a subclass.



Knowledge and, especially, practical experience, are the best way to learn. But after all, refactor is a matter of hunches.

In my next post I’ll be speaking about design patterns, which are just a deeper level on the eternal wisdom of refactoring.

SOLID principles

I’m applying for a job in a frankly interesting company, so I’m reviewing all the good programming practices I was taught and learned during my career. Those are essential for developing good code, however an alarming number of “programmers” don’t really understand them (or actually never heard about them).

In this and subsequent posts I will try to explain fundamental coding principles, refactor techniques, design patterns and so, as clearly as possible, and probably using ailuromaniac examples. Today we’ll speak about the SOLID principles.

SOLID defines the five basic principles of object oriented programming. When applied together, these principles will make a software easily maintainable and extendable. wiki



S – Single responsibility principle wiki


A class should encapsulate only one responsibility, and that responsibility should be entirely encapsulated by the class.

Robert C. Martin relates the concept of “responsibility” with “reason to change”:

A class should have only one reason to change


Take a look at this class:

It is obviously bearing with more than one responsibility because it has methods for a lot of different and unrelated actions. For instance, setSkin has nothing to do with calculatePathToDestination, because the color of the kitten’s fur has no effect on the calculation of a path.

From another point of view, this class may be changing for several reasons: changing the implementation of skin, changing the implementation of any of the AI branches…

The right implementation encapsulates each responsibility within objects, and the class Kitten is only dedicated to gather those objects by composition:

Now each class will have its own reason for change, and Kitten will barely do.This also means that when a class changes, none of the others will be affected by this change.


O – Open/closed principle wiki


A class should be open for extension, but closed for modification. This means that your super classes should be enought generic to be extended by their childs as they are.


In the code below, the class Cow extends the class Animal and implements its abstact method eat:

This does not work, because cows are vegetarian, but we are forcing them to eat meat.

But if we abstract the type Meat into an interface, such as Food, not only cows, but all the animals will be able to use the eat method as they prefer:

Meaning, the Animal super class is enought generic to be extended by a large and diverse amount of creatures as it is, without modifications:

And they will be happy and forever live in harmony.



L – Liskov substitution principle wiki


In my opinion, this is one of the more complex and misunderstood principles, along with the dependency inversion principle.

It states that objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program. Also explained this way:

If S is a subtype  of T, then objects of type T may be replaced with objects of type S.

Yeah well, this is quite abstract, let’s see it on a practical example.


Here, our classes Kitten, Dog and Scorpion extend Animal and override its method pet():

If we try to replace Animal by Kitten, the system will fail, because the method pet() overriden by Kitten does not work in the same way as beHappy(). Same for Dog. And Scorpion does not even need the pet() method because seriously, did you ever try to pet a scorpion? Moreover, it breaks the YAGNI principle.

We cannot replace the type Animal by these subtypes. This violation can be solved extracting the pet() method from the superclass to an interface, this way:

So now you could replace the type Animal by any of its subtypes, and it will still work, because pet() is no longer Animal‘s method, but Touchable‘s method instead.


BUT pay attention, because the code below does NOT violate the Liskov principle:

This implementation respects the principle because, as long as the precondition gluttony = 0 is true, the class Animal can be replaced by its subtype  Kitten and the system will be delivering the same result.

One of the best things about Liskov’s principle is that by applying it you are unconsciously forced to program by composition instead of inheritance, which is also a very important principle.


I – Interface segregation principle wiki


Many client-specific interfaces are better than one general-purpose interface.

Your interfaces should be as small and specific as possible. This will allow you to reuse them and also to avoid forcing classes to depend on methods thay they do not need.


Here’s a “general-purpose” interface named IPhysicalEntity:

As you can see, it gathers everything that a physical entity may need. Here are some classes that implement this interface:

Notice that many methods were not actually needed. But if we split our huge interface into smaller ones, this way:

Then each class will only implement the interfaces that is needing at this moment, and we can get rid of unused code:

You can eventually add or remove interfaces from your classes as the specs change.

Personally, I like this principle because it makes classes more readable, for instance, extending the example above, you can quickly know the properties of an object:

It’s just like reading prose: Kittens can move (Mobile), can be petted (Touchable), can be set as a target (Targetable), and so on.


D – Dependency inversion principle wiki


Depend upon abstractions. Do not depend upon concretions.



This violates the rule because the object kitten is declared using a concrete type (Kitten). This is how you should have done:

We declare the object as a generic Animal, and then we assign to it an instance of the concrete type we want that animal to be.

It’s quite simple and actually I don’t think the problem with this principle is that it is misunderstood, but more like it requires a very much strong self-discipline. For instance:

Would you say that this code is SOLID?:

behavior is (very OK) declared as a generic type (Behavior). But then, in the constructor, we are assigning it an instance of KittenBehavior, which is a concretion. And we are giving this responsibilty to Kitten. From now on, our class Kitten will be eternally coupled to the KittenBehavior type.

But if we do this way:

And decide the type in the invocation:

Then Kitten will no longer depend on this concretion. This technique is called dependency injection, and allows us to indeed inject the concretion from outside the class, releasing it from a responsibility that does not deserve.

You could now change KittenBehavior by WhiteKittenBehavior, CatBehavior, or whatever XBehavior you’d like, yet Kitten will stay functional.



I’ve always been an organized person. Some people may call it OCD but well, I don’t think it’s so bad.

So you could say SOLID was an epiphany for me, because before we met I was very uncomfortable with my code but didn’t know exactly what was wrong with it. Now I know that EVERYTHING was wrong. From that day I’ve learned quite an amount of techniques and rules, and honestly, the more I discover, the dumber I feel.

Unfortunately what Kent Beck said here was true:

Adopt programming practices that “attract” correct code as a limit function, not as an absolute value. [...] you will create what mathematicians call an “iterative dynamic attractor”. This is a point in a state space that all flows converge on. Code is more likely to change for the better over time instead of for the worse; the attractor approaches correctness as a limit function.

The painfully implication of this statement is that, despite our efforts, our code will only pretend to be good, but never achieve absolute perfection.

But well, you will always be closer to perfection if you are well trained, so I’ll try to gather and demystify some of the key coding skills here. Besides, trying to clearly explain something is one of the best ways to realize that you actually don’t understand it.

In another vein, during this post I’ve been doing what we know as Refactor, a process through which the code is reestructurated without changing its external behavior, aiming to improve the quality of the software. I’ll be writing about it later in this blog, but if you feel intrigued read this.

Also in the incoming posts we’ll explain some design patterns and, buddy, you should know about them.

Refactor to MVC

Hi! It’s been a while since my last post. My live has changed so much! I finally left my dryasdust work at a large IT consulting company, and got another job at a small Dutch company. Dutch people rock! I changed my job, I changed my house, I lived all new kind of experiences in different countries… And I also changed my mind! Now let’s code again!

Today I’m going to explain how I managed to refactor the old structure to fit MVC pattern. To make it short, I’ll explain what MVC is, and then make a practical exercise to understand the implementation.

You won’t need to download the game code to be able to follow this post, but, if you feel curious, here’s the direct link to the GitHub repository. You can also find the last compiling build in the Download page.


1. MVWhat?

M: Model.

V: View.

C: Controller.

This pattern helps us to encapsulate responsibilities. As you start programming a videogame, or any other program that has a UI, you will probably glimpse a grouping of functionalities: The stuff in charge of the interaction with the user, the stuff in charge of data, and the stuff in charge of internal calculations. MVC architecture allows you to cleanly split these groups of functionalities.

There exist lots of books that describe MVC, but if I could recommend one, I’d choose “Head First Design Patterns”. This book is very funny and easy to understand. Let me use its diagram to explain what MVC is:



Here! I told you it was a good source. As you can see in the diagram above:

  • The View is the UI. As the user sends an input, the View will notify the Controller that something happened.
  • The Controller will take that notification and will notify the change to the Model.
  • The Model will change its data depending on the parameters received, and then it will notify everyone that he has changed.

Well, this is quite a sober explanation; I don’t want to get you confused. Keep those three concepts in mind and start reading the implementation, where it will probably become clear to you.

2. Implementation

2. 1. Extracting Model and View

There’s something in the refactor process that we call “smells”. Martin Fowler describes code smells like this in his book “Refactoring – Improving the Design of Existing Code“:

Certain structures in the code that suggest (sometimes they scream for) the possibility of refactoring.

You can find a catalog of code smells here.

Now take a look at this class. Look at the comments, yet in the first lines of code:

Doesn’t it smell a bit? What those comments are doing, is to separate the UI variables from the Data variables. “nekomata” is an Actor, and “dynamicBody” is the Body. In other worlds, nekomata is the picture of the kitten that is shown to the user, and dynamicBody is the calculated data that is processed internally.

This is a clear example of Data Clump, wich must be fixed using Extract Class, which means, to create classes that enacpsulate those variables and methods that can be decoupled.

Let’s do it little by little.

First, we will create three new classes:

-       KittenView

-       KittenModel

-       KittenController

The last one may not have much sense now, but don’t worry for now.

Next step consists in identifying which part belongs to which class. You can try yourself, or you can take a look at this code, where I’ve added some comments to make it easier. A technique that works for me is to move the variables already identified, and then look at the compiling errors. They will give you a hint about which components must be moved.

You must also mind the class implementations and extensions. In this case, the class “Actor” corresponds to the view and “ICollisionable” must be implemented by the model, this way:

Now start moving each element from Kitten to KittenModel and KittenView. It is important to know that the Model is a standalone class, it should be decoupled from the other elements of MVC. So it is a good idea to start the refactor with this class.

Here’s the result:



Notice that KittenModel only contains its own elements, while KittenView needs model’s information. For example, in the method “UpdateAnimation”. As explained before, the View changes the animation depending on the Model’s data. It needs to know the velocity and angle of the physics simulation to show a concrete animation:

2.2. Implement the MVC pattern

Now that we’ve assigned the responsibilities, it will be easier to implement the MVC pattern. I will try to explain how I did it, but if you don’t like my style you can find other implementations over the net.

This is how my structure looks like:


The Model is observed by the View. To make it observable, I used PropertyChangeSupport and created this class, meant to be extended by Models:

Then use “notifyUpdate” when the data changes. For example, when the position changes:

Next, we must prepare de View to get those notifications. To get this done, make the View implement PropertyChangeListener, and override the propertyChange method to manage the notifications received:

Good! Now the only thing that left to do is create the Controller to put all together. You will find the complete implementation on a link later but, for now, to focus on what the controller actually does, read the code below:

When the game asks the KittenController to create a new Kitten for him, the KittenController will create both the KittenView and the KittenModel, subscribe the View to the Model’s notifications and, finally, add the Kitten to the World:

There we are! Almost done. Just let me explain briefly how the user’s input will finally modify the Model.

In the game, when the user clicks on the picture of a kitten, drags, and then releases the cursor, the kitten will start moving to the point where the cursor lifted (the Waypoint). But actually, the view does NOT move anywhere by itself. What really happens is that the user sends an order to the View. The View notifies the controller that the user dragged the cursor. The Controller asks the model to react to a cursor drag. The model makes the physical object move to the Waypoint, and this action fires a PropertyChanged event that will be cathed by the View.

This way:



And this is how all works together. I think I’m not forgetting anything, and that the explanations where understandable… I’m leaving the final implementation below, that way you will have an overview:





This was quite didactical :) I like how the post looks like. I’m not sure what to do next. I’m curious about the skeletal animation. I’ve been nosing around Spine… Or maybe I should start making something more concrete, like a first level? I’ll think about it.

Thanks for reading! Don’t forget to share and comment! See you soon ^^