Refactoring at ORUG 2

Posted by caike on January 19, 2010

Here is the slides for the Refactoring talk I did last Thursday at the Orlando Ruby User Group meeting. In case you want to hear me speaking along with the slides, I’ve put it up on vcasmo also.

Autotesting PHP applications (and others) 3

Posted by caike on January 12, 2010

So you’ve probably heard of ZenTest/Autotest, right?

In case you haven’t, it is a Ruby gem that (among other things) automatically runs your tests whenever it notices that a file in you project has changed. It’s a great productivity boost, because it saves you from having to run your tests each time you make a change to your program. The perfect tool if you are doing TDD.

So I wanted to get this autotest functionality going for projects in other languages - like PHP, for example - but apparently ZenTest/Autotest only works within Ruby projects.

Talking to the EnvyLabs’ guys I was told about Watchr, a Ruby gem that monitors files matched by a regular expression and triggers a user defined command whenever a file changes. That’s enough to get you started in an autotest-like tool for PHP - or just about any other language.

I’ve setup an example PHP project of Watchr playing an autotest role in a PHP project:


View on Vimeo.

The source code from this example can be seen at http://github.com/caike/watchr_running_php

Writing expressive code 7

Posted by caike on October 07, 2009

Software developers read a lot more code than they actually write. An application source code is nothing but a story written using a specific language. It has state and describes behaviour.

Code written once, will be read millions of times. For the most part, it will be read by a compiler who doesn’t really look for anything but correct syntax. Compilers are not into reading stories. They are too busy for that. Just like assembly-line workers, they follow a plan and do exactly what they were told. As soon as they pass things over to the runtime, they are done. On the other hand, we developers are not like that, are we ? No, we are not!

We are software craftsmen. We like to read stories and even get paid to write some every once in a while.

man_reading_book

http://www.flickr.com/photos/dhammza/91435718/

Think about it the next time you hack that magic one-liner in an application. Do you think you will be able to read that code-golf champion piece of code the next time you look at it ? What if it is not you, but someone else reading it ?

“Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live (…) Alternatively, always code and comment in such a way that if someone a few notches junior picks up the code, they will take pleasure in reading and learning from it.” - Ward Cunningham, CodeForTheMaintainer

An example I like to use for expressive code is method parameters in Ruby. Let’s say you want to stay fit and write a method to calculate a body fat percentage. You write the following:

def body_fat_percentage(name, age, height, weight, metric_system)
end

Apparently it looks nice. Let’s see how it could be invoked:

# fred's height in meters and weight in kilograms
body_fat_percentage("fred", 30, 1.82, 90, 1)

# barney's height in feet and weight in pounds
body_fat_percentage("barney", 32, 5, 300, 2)

In order to write those two calls you would probably have to check the right order for the parameters in the method’s signature. Even worse, every time you read that line you would have to check back its signature just to make sure that the last argument determines the metric system or that the third argument is actually the height and not the weight.

That sounds like a pretty boring story to read!

Let’s make this piece of code more expressive:

# fred's height in meters and weight in kilograms
body_fat_percentage("fred", :age => 30, :height => 1.82,
  :weight => 90, :metric_system => MetricSystem::METERS_KG)

# barney's height in feet and weight in pounds
body_fat_percentage("barney", :age => 32, :height => 5,
:weight => 300, :metric_system => MetricSystem::FEET_LB)

All we need to do to the method signature is to replace the standalone arguments for a hash.

def body_fat_percentage(name, params={})
end

From the method body, the values can be accessed using the keys, like params[:age], params[:height], etc.

In a real life situation, this expressiveness would be achieved from writing our expectations as unit tests. We would first write our failing tests as how we wanted our code to look and act like. From that, we would head towards making the tests pass. When all is green, the tests would turn out to be the reference for how to call the method (running and never-obsolete documentation) so there’s no need to go back to the implementation of the method itself to learn how to to use it.

Writing expressive code often means writing more code, but it also means writing better code. It’s not about making things work, it’s about making things right.

O conto do lenhador 7

Posted by caike on September 01, 2009

Não lembro ao certo quando escutei este conto pela primeira vez.

“Certo dia, um rapaz que caminhava pelo bosque avistou um lenhador tentando derrubar uma árvore. Observou-o por alguns instantes e notou que, mesmo investindo cada vez mais força em suas machadadas, não estava obtendo muito sucesso em derrubar a árvore.

Então o rapaz sugeriu ao lenhador:

- ‘Por que você não descansa um pouco e, enquanto isso, aproveita para amolar o seu machado ?’

O lenhador respondeu:

- ‘Não posso perder tempo! Tenho que derrubar logo esta árvore!’”

Desenvolvimento de software é um processo contínuo de aprendizagem. Diariamente nos deparamos com árvores a serem derrubadas. No caso das mais difíceis, pense em parar e refletir sobre o que está fazendo enquanto amola seu machado ao invés de ficar repetindo incessantemente a mesma coisa, esperando resultados diferentes (a definição de estupidez, segundo Einstein).

Machado

http://www.flickr.com/photos/shedboy/3610432084/

Você reserva algum momento de sua semana para a leitura de blogs de referência da sua comunidade ?

Participa de alguma comunidade ?

Participa de pelo menos uma grande conferência por ano ?

Está lendo algum livro técnico ?

Estar atualizado é responsabilidade de qualquer profissional de tecnologia.

Coding Dojo CESUPA 8

Posted by caike on July 07, 2009

Na última sexta-feira tive o prazer de realizar um Coding Dojo junto ao pessoal do CESUPA, em Belém do Pará.

Ao todo, nove pessoas estavam presentes. Paulo Igor, Marcos Venicius, Aldrin Leal, Gustavo Pinto, Igo Medeiros, Mateus Miranda, Danilo Cunha, Rafael Santana e eu nos reunimos as 16 horas (horário mais conhecido como “depois da chuva”) no campus José Malcher, sala 4F, munidos apenas de um pc e um retro-projetor.

Enquanto aguardávamos o resto do pessoal chegar, Paulo Igor, Aldrin Leal e eu conversamos sobre Ruby, Python, FISL e sobre o Project Zero, um projeto ao qual o Aldrin pertence.

Após uma pequena apresentação do que é o Coding Dojo, sugeri alguns problemas que poderíamos resolver. A maioria optou pelo problema do jogador de futebol, que já havia sido resolvido em Ruby no último Dojo Rio mas que desta vez seria resolvido utilizando Java.

O problema mostrou-se mais uma vez de fácil compreensão e não precisamos de muito tempo para a definição das estórias. Gosto do formato de user stories para fechar o escopo de problemas como este (e como o wowspec) para um Coding Dojo, uma vez que são idéias muito gerais e com possibilidades  de implementação quase que infinitas.

dojo cesupa

A utilização do Netbeans como IDE não foi uma boa escolha. Com apenas duas classes, o Netbeans foi capaz de se perder e exibir testes falhando mesmo quando corretos. A solução foi dar ‘clean’ no projeto de tempos em tempos.

coding dojo cesupa

Após 40 minutos de codificação, conseguimos completar as quatro estórias criadas mas não tivemos tempo para refatorar nosso código. Como o objetivo do Coding Dojo não é completar os problemas, mas exercitar ao máximo as técnicas de programação e comunicação durante o time-box estabelecido, paramos de trabalhar no código e passamos para a retrospectiva.

Realizamos nossa retrospectiva e trocamos muitas idéias sobre, claro, metodologias e práticas ágeis e também sobre a situação do mercado de desenvolvimento de software em Belém, que carece de profissionais que pensem ‘out-of-the-box’.

Obrigado ao CESUPA pela disponibilidade da sala e equipamentos e também aos que estiveram por lá e participaram do Dojo. Espero que tenham gostado e que possam levar a prática do Coding Dojo a diante!