Code Smells – Part I

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.

So what are code smells?

As Martin Fowler said in his book “Refactoring: Improving the Design of Existing Code”,

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:

  • Bloaters
  • Object-Orientation Abusers
  • Change Preventers
  • Dispensables
  • Couplers

Today I’m going to talk about Bloaters. I’ll leave the other categories for a future post.

Bloaters

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.

Primitive Obsession

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:

Then we can do it for the parameters of the request:

With all this in place we are now ready to create a XMLRPCRequest:

We can also extract a method with some display updates:

And last but not least we can extract the preparation for displaying the error message:

With all these extractions our method now looks pretty neat:

Hmm… we can do this even better! Let’s take a look at the method createXMLRCPRequest and see if we can call the others from there. In this case, it makes sense to have all together.

And our original method now looks like this:

Well, here you go: a method with more than 5 lines and I think that’s ok. 🙂
As we can see it’s really easy to let a method grow. But it’s really easy to refactor and have a cleaner code too.

Conclusion

In general, bloaters are viewed as code that, over time, “gets out of hand”.
Remember, code smells sometimes can’t be removed, but it’s good to know that they are there and you know why they are there.

Talk to the business

Almost a month ago, I did this amazing course at SkillsMatter: “Eric Evans Domain Driven Design Immersion Workshop”. The course was very intensive and provided me with the opportunity to reinforce a lot of concepts I already knew as well as learn a few more.

One of this concepts was Ubiquitous Language. The first time I heard it from our coach Alberto Brandolini, I must confess I understood “Ambiguous Language”. The term “Ubiquitous” it’s not a simple one, essentially for a non-native English speaker like myself. While I was listening to the coach explaining all of this concepts around the “Ubiquitous Language”, another one did made its way through: “Bounded Context”.
Martin Fowler has a really nice post where he defines it like this:

Bounded Context is a central pattern in Domain-Driven Design. It is the focus of DDD’s strategic design section which is all about dealing with large models and teams. DDD deals with large models by dividing them into different Bounded Contexts and being explicit about their interrelationships.

One thing that Alberto told us was that we should always consider our bounded context when talking to the business expert: in the same company, different concepts may be used for the same term, when you are talking to sales expert or accounting expert. So it’s up to us, developers, to define in which context we are currently working.

The videos that they showed to us during the course were very helpful: I definitely saw myself in previous clients doing the same mistakes and not understanding what was going on. The good thing is that now I know how to address it, and even did it twice in my current client.

So the next time that you hear a business expert using a different word from the ones that your using, go and talk to them. Make sure the words you are using are the correct ones, and if there’s a new one then you should integrate it into your model. After all they are the ones who know the business!

How katas can help you learn

Baton_long by Alain Delmas

In the last couple of weeks I have spent my time doing katas to improve my Objective-C. As you may remember, I had an issue, that you can revisit here.

I’ve learned a lot from other katas too: for instance the RomanNumerals kata… You’d may think it’s a simple task, that you wan’t learn much from. It’s a simple algorithm, a good exercise for your red -> green -> refactoring cycle. So nothing new will come from here… Wasn’t I wrong!!!!!

First I created some tests. Next I implemented the kata and refactored. Whilst I was refactoring, I decided to use NSDictionary to map from a decimal to a roman number. Here is an example:

That’s when I discovered that the NSDictionary does not guarantee insertion order. What???? So my keys were all mixed up… And I needed them to maintain their order!!!! That’s ok! I decided to create a class to map between decimals and romans. That’s cool! Done! In the converter I just added a private property of type NSMutableArray. In it’s constructor I added the class to the array for all elements I needed. But now I have to do:

for every entry in the mapper. God!!!! So much work! Maybe that’s why developers solve problems. They definitely don’t like to do things by hand so they automate everything.
So I decided that I could create a factory method. I really didn’t know how to create this factory method, so I just looked in Apple docs. Here is another thing i learned. Even thought I knew that it existed, I never used it because I never needed to. But as I was in learning mode, I think I was more interested in finding a different way to do it. When you are at a client, you don’t always have the opportunity to experiment with new things. Having this time to learn new ways of doing things is really rewarding. So here is my class:

It’s even more readable then the initialiser. And here is how I initialised it in my converter:

So my class was looking pretty but then I look at my test class…it wasn’t good:

So many tests. They remind me of the DRY principle. I really don’t like to repeat myself. It’s like a broken CD that doesn’t move from the same music track… I’ve done the same kata in C# and my test class was all parameterised and I really liked it. After all this is a simple kata, right? ;).

Well wouldn’t it be nice if I could have that in Objective-C? Well, after some help from Franzi I found a little library that does it. You install the pod, you inherit from it and you create an array of inputs and expected values like this:

And then you just have to use the properties input and expected. So my test class looks like this:

Here is my final solution: RomanNumerals.

So please don’t underestimate what you can learn from a kata. They are a good opportunity to stretch your knowledge and add some more to it!
image: Baton_long by Alain Delmas

Testing Categories in Objective-C

Yesterday was katas day: the plan was to start the day with a simple one and then move to another a little more difficult. That was a good plan.
So I decided to do the Stack: a very simple kata, I just had to simulate a stack and have the following methods:

And for rules just this one: “stack should throw an exception if popped when empty.”

Simple right? I thought so too. And it was really easy to solve it: just create a NSMutableArray category and add the methods to NSMutableArray.

So I create I first test :

So I create my class and my code and everything builds! Great, just run the tests and that’s it! No it isn’t!!! Here’s the result of my test:
CategoryTestError

What? So the code builds and then I have this error:”unrecognized selector sent to instance”. Well let’s ask google….
In reality it took me all morning to figure it out! I must improve my search techniques!!! After googling a lot and a lot of frustration, I find a blog post that saved my day: So if you want to test a category you must add -all_load flag to your test project. Go to: YourTestTarget > Build Settings > Linking > Other Linker Flags.

Problem solved!
You can find my final solution here.

Starting your TDD journey

The old story always comes around when talking about tests: it takes too long to do them and we loose a lot of time. Well, everything is hard to do if you are learning it. You need to practice and practice and practice to become proficient in any new skill.

Let’s imagine you want to start playing tennis.  What can you do to achieve your goal? You register in the tennis club near you and you start training. You go every week days. 4 days you practice with the machine that throws balls at you, and the other day you practice with a coach that shows you the technical skills you must develop to become a good tennis player.

So why not do the same when talking about developing a new skill as a developer? Why not start your day with a kata to enhance your TDD skills. Nowadays there is a lot of sites that provide small katas in several languages. There are a lot of then that have the solution so you can see how others have approached the same problem.

Going back to tennis, do you think that after a week you would be able to play against Rafa Nadal or Andy Murray?  And after 6 months? Probably only after 5 or 6 years you would be able to be at there level.  So why think that after a week of trying TDD you should be super efficient and be the best of it? Do you think that Uncle Bob or Sandro Mancuso were proficients in TDD after a week? After 6 months? If you want to be good at something you must practice. What better place that at work were you can beneficiate from having good tests that will improve your code and reduce your bugs?

So now  you can start your journey into TDD knowing what you should expect from yourself: hard work! If you google “kata” you will find a million links to kata sites, Github repositories, there’s a lot of examples in the net, so just put your hands on it.

There’s really no excuse to not do TDD. Well then you’ve got the skeptical one’s that don’t believe  that “wasting your time doing tests” will improve in any way your code or your way of thinking about your code.

If you really want to embrace TDD, and you feel you have a lot of resistance from your colleagues and manger, the best is look for a job in a company that looks at TDD as a fundamental tool for their developers to be great at their job. They are around. Not so many as you expected but the number is growing.

New professional experience

Hi all!Watch movie online The Transporter Refueled (2015)

In the pass 2 to 3 weeks I’ve been living a new experience, and I just feel like I should somehow put it down and share my new journey as an apprentice that aspires to become a software craftsman at Codurance.

I already have a lot to talk about, but today I would like to talk about my recent experience in SocratesUk conference. This is my first conference for a long time, I don’t even remember the last one I attended. There were lots of reasons that kept me away from conferences and now I just come to this one and really had a lot of fun. And that’s for me what really changed from what I remember of what is a conference: the fact that I had fun, didn’t get bored with some infinite lecture that I could not leave. I could talk with everybody and even propose a session if I wanted. SocratesUk is a no conference, and has a very loose format that I loved.  You could suggest topics that you’re interested in and just announce it in the board, and people with the same interest would just appear the informal spaces available and talked about that.

I must confess that I’m a little shy, and the first day was a little difficult for me to approach others, introduce myself and join a group of people, but in the second day as with had been in the talks you know some people and it’s easier to break that initial ice.Watch Full Movie Online Streaming Online and Download

I think I can say that I’ve made some friends, and I that I really met some amazing people that I want to at least try to maintain in my professional and personal network.

See you around!

 

…subir e descer escadas a torto e a direito!!!

Que canseira! É tudo tão bonito, quando de propões a viver numa casa: novas ilusões, novas esperanças, pequenas coisas que arrumar aqui e ajeitar ali. Enfim o normal de quem deixa tudo para trás e começa tudo de novo, mas sabendo-se rodeado da família. A casa prometia e muito como se pode ver na foto:

Casa_Londres

 Watch Full Movie Online Streaming Online and Download

A nossa parte corresponde às 4 janelas sobre a parte azul, onde vive o nosso vizinho. Por aqui dá logo para entender que subir e descer escadas é “o pão nosso de cada dia”.  E o pior de tudo é quando tens que lavar roupa (faço uma maquina cada dia! É verdade somos 5, bem agora com o sobrinho encrostado somos 6!) e a máquina está no 2º andar!!!! Lembro-me tão bem de que quando casei queria um duplex, que achava que devia ser muito prático…pois tinha 25 aninhos…agora já passados os 40, não há vontadinha nenhuma de subir e descer escadas como uma louca… Estas são as malditas:

escadasO bom disto tudo é que se faz muito exercício de tanto subir e descer escadas… (tenho pena do meu vizinho, coitado, que leva com 4 miúdos a correr escada a cima, escada a baixo…nem quero pensar nas pragas que nos deve rogar cada dia!)

Até logo!

…é encontrar uma raposa pelo caminho

É verdade! Desde Setembro que caminho todos os dias para o ginásio e de vez em quando lá estava ela: olhava para mim como quem dizia: “Que queres?” E o mais difícil de todo foi fazer coincidir a raposa com o meu telemóvel. Parecia praga: quando me lembrava de levar o telemóvel, não se via raposa em parte nenhuma… no dia que me esquecia, lá estava ela toda pimpona… Finalmente há umas 2 semanas atras os 2 coincidiram e o resultado foi este:

fox2 fox1

Ok! Já sei que as fotos não são da qualidade e beleza que o meu amigo João Bastos, mas esforcei-me! Também, não se pode exigir mais às 6:45 da manha!!!!!

Beijocas,

 

…é ter a oportunidade de conhecer o meu sobrinho!

É verdade! Saí de Portugal há 9 anos para ir viver para España. O meu sobrinho tinha 10 anos. Se o vi entretanto, foi tudo entre visitas fugazes a Portugal, e portanto não posso afirmar que o conhecia. Afinal na puberdade é quando mais uma pessoa se afirma e forma a sua personalidade. Quando estávamos cá em Agosto de férias, o meu sobrinho já cá estava a morar e a tentar refazer a sua vida. Encontramo-nos para almoçar e, devo confessar, que com boa impressão dele não fiquei: Estava super magro, com piercings por tudo o que era sitio visível na cara linda que tem, e vestido à havy metal o algo que tal. (Na foto não se ve muito bem, mas acho que se entende bem de quem falo 😉 )

Sobrinho

 

E como sempre os ditados populares têm sempre razão: “quem ve caras não ve corações”.  Quiz o destino que, por varias razões, deitássemos uma mão ao rapazola, e ele veio para cá viver em Setembro. E nós passamos a conhecer o Tiago, que era um autentico estranho para nós. E parece que afinal o miúdo, saiu melhor do que parecía: debaixo dessa capa de dureza e provocação, encontra-se un teenager com muito que provar e conhecer, com momentos de rebeldia e otros mais de responsabilidade e  como é normal passou a ser mais um da familia.  Hoje começou uma nova etapa. Que seja boa e duradoura.Watch movie online The Transporter Refueled (2015)

Até logo!

…viver em Londres!

kveen0682s

Depois de 9 anos a viver em Espanha (1 ano em Madrid e 8 em Barcelona), decidimos mudarnos para Londres. A mudança foi mais fácil do que esperávamos, essencialmente para os miúdos (se bem que depois de mudarmos de casa 6 vezes, das quais 2 foram mudanças de país (primeiro para Madrid e depois para Barcelona(sim, Catalunha é um pais, e fala-se uma lingua diferente, essencialmente na escola)), é certo que não esperávamos grande resistencia por parte dos mais pequenos. O facto de os termos posto no instituto espanhol, ajudou muito, porque não tiveram que aprender imediatamente uma lingua nova. E, outra coisa muito interessante, praticamente todos os colegas eram novos na escola.

E assim, rapidamente voltamos à rutina cá em casa: o P. vai todos os dias trabalhar, os miúdos vão a pé para a escola e eu vou para o ginásio e depois volto para casa para trabalhar nos nossos projectos. Tudo igual como antes…Como é viver em Londres me perguntam? É igual que viver em Barcelona, só que aqui as pessoas falam inglês 😉 ! Ao contrario da Susana, de quem tenho seguido as aventuras, mudar-me de país não teve esse impacto na minha vida. Agora não o teve, mas sim quando nos mudamos para Madrid e depois para Barcelona. Agora os miúdos já vem a vantagem que é serem, de momento trilingue (Português, Espanhol e Catalão) e a grande vantagem que terão quando forem poliglotas e dominarem totalmente o inglês.

Até logo, divirtam-se!!!!Watch Full Movie Online Streaming Online and Download