Archive for December, 2011

RS: Trazabilidad

En la retrospectiva de esta semana hemos hablado sobre todo del proceso de desarrollo. Nuestro proceso se apoya en kanban, no hacemos scrum. Scrum es demasiado lento para la velocidad con que nos entran peticiones de cambio de funcionalidad. Nuestros sprints son de una semana y el objetivo es la entrega constante.

Lo que ha sucedido esta semana es que las tareas terminadas se han acumulado a las de sprints anteriores y hemos perdido la información de qué funcionalidades se estaban entregando. La solución que se nos ocurre es que la persona que recoge las incidencias y se encarga de notificar a los clientes de su resolución y de nuevas funcionalidades, esté presente en las reuniones 

diarias (daily stand up meeting). Además las tarjetas del kanban estarán tambien en nuestro trac, cuando coincidan con historias de usuario (hay tarjetas más pequeñas que una historia de usuario). Intentaremos que todo el mundo conozca el estado de una funcionalidad desde que se escribe la historia de usuario hasta que se notifica al usuario su puesta en producción. Para ello, todo el mundo es responsable de ayudar a definir bien las historias de usuario, si van a entrar en el WIP (work in progress) y nuestro dueño de producto no ha tenido tiempo de estudiarlas a fondo. Cada uno se reponsabiliza al coger una tarjeta para implementar, de que se finaliza, de que no se queda nada atrás y también de que se avisa de cuándo está subida a producción.

Esta semana toca hacer pruebas de carga de nuestros sistemas para estar seguros de la cantidad de conexiones que podemos aguantar con la puesta en marcha de nuestro nuevo producto. El objetivo de las pruebas de carga no es lanzar muchas peticiones contra el servidor y ver que aguanta, sino hacerle peticiones hasta que se caiga, y entonces tener la medida más precisa posible de hasta cuánto aguanta. Lo contrario sería un falso positivo.

Por otra parte, el haber elegido javascript como lenguaje principal para las nuevas aplicaciones, ha aumentado temporalmente el bus factor y los viernes estamos haciendo sesiones formativas sobre el lenguaje, aunque necesitamos que todo el equipo lea libros en su tiempo libre. En otras circunstancias no pediría al equipo que leyese en su tiempo libre temas profesionales pero siendo una empresa de poco tamaño que tiene metas tan fuertes, no queda más remedio.


Javascript, an acquired taste

You hate it, you love it

You start hating it but you might end up having so much fun with Javascript. It takes time to acquire the taste and enjoy the powerful capabilities that annoy you at the beginning. This is my experience learning this popular language.
Take into account that my opinion is based on just a few months of experience with Javascript as a language, not just a tool to manipulate the DOM (html and css). It will probably change along the journey.

The white box

Being used to languages like Python, I'd say Javascript is a white-box language while Python is a black-box one. That is, you don't really need to read books to start coding in Python, you just see some example code, try some lines and usually its execution behaves as you expected. It feels so natural. That is not the case of Javascript, its rules are not natural at a first glance. In fact, you have to know very well how the interpreter makes decisions. If you make a mistake writing some code that wouldn't compile or would raise an exception on other programming languages, Javascript will instead try to execute the code. And will probably traverse all the execution path. Because it doesn't fail, this behavior can be very confusing and hard to detect. You wish the interpreter to tell you that, you made a mistake and you probably didn't want to write what you did, you don't want the execution to continue. That is the feeling at the beginning. On the other hand, as time goes by, these capabilities turn out to be so powerful in terms of implementation choices and performance tuning.
Unfortunately coding for performance tuning leads to code that is hard to understand and maintain.

TDD is a must

We've been pairing and test driving our Javascript code these months using Jasmine.  I feel that the impact of BDD on Javascript is bigger than on any other language. It's mandatory. I don't want to write a single line of production code if there is no failing test asking for it. Because Javascript forces me to be smarter than I am sometimes and ocuppies part of my mind with subtle implementation details that moves me away from writing code that expresses the business domain, the semantic of the actual business problem to solve.
If I don't write a test, a specification that clearly states what I expect the code to do and see it pass, I can't bet that it will work just by looking at the production code. It would feel like gambling.

There is a tone of patterns to avoid tipical Javascript mistakes. There are many books on the subject. Experts advise you techniques like, "check the type of the arguments the function receives, to make sure you get what you expect". But then they tell you that "instanceof" operator might not work if the inheritance wasn't implemented properly. It is overwhelming. I tell you a secret... you don't need to master all those patterns if you test drive your code! You don't have to worry about all possible usages of your code if it's you or your team who are going to consume it, because the specifications are already thought, written and are executable.

I always prefer "duck typing" than asking for the type of the arguments. I usually prefer to let Javascript evaluate conditions using its coercion rather than using strict  operators like "===" or "!==". Because if you write code for humans, it is better to say:
"if (userExists)"
"if (userExists === true)".

So the approach and the concerns are totally different when you test drive the code. The productivity gain is brutal. Javascript is too expensive to work with if you can't guarantee all the time, that your code functions as you inteded it to be.

If for some reason I would not be able to develop with BDD, I would code with Coffescript rather than Javascript 🙂

The approach is totally different if you are writing a framework. Frameworks are too general, they are horizontal, not vertical so there is no business semantic on them. So yes, for frameworks you should be a Javascript power ranger.

OOP or Funtional?

Javascript is not a classical objet oriented language. There are no classes. However is a great language for object oriented programming! Don't be confused with this. If you know the object oriented paradigm, you just need to know how to implement polymorphism, composition and so on. The discussion on "there are no classes, there are prototypes", is superfluous. It is an implementation detail I don't care about. I don't think that is really important because I can express behavior with objects and model the domain the same way I would do it in Java. Rather than using "class" and "extends" I would use "constructor stealing along with prototype chainning". But it's the same tool 🙂

On the other hand, javascript is a great language for functional programming too 🙂 It is actually more used as a functional language than as an OOP one. It is very common to pass functions as parameters and things like that.

You can approach different paradigms with Javascript. My advise is to not mix them together though.

Programming the UI is fun again!

I used to write desktop applications using Delphi, pyGTK and Windows Forms at the beginning of the past decade. When the web started getting mainstream, it was sad to say goodbye to all the best practices learned all those years. Used to the power of event oriented programming, rich components, data binding, and design patterns in general, developing for the web felt a step back. During the past decade there have been many attemps to mimic the old desktop in the web; portlets, asp webforms, and so on. None of them made developers happy, so the Model-View-Controller (MVC) pattern came to the rescue. However, dealing with the UI is still something developer don't really use to enjoy. DOM manipulation has been a pain in the ass with every browser having different behavior and API. I've been trying to avoid it until now and, to be honest, I am happy to not have invested my time fighting with problems that jQuery handles for me nowdays.

Now, ECMAScript 5 is supported in all major browsers. jQuery and other frameworks make life easier. And there is something that we didn't have in the old desktop programming: the chance to programmatically interact with widgets (UI controls or components). Well there are some frameworks for that in the native desktop, by they came late. This means that we can write automated tests for UI behavior!

So now, we have the chance again to use event driven programming, to really implement patterns like the "observer" and many others. And we can test drive all of them!
We can develop semantic components that add domain knowledge inside UI widgets and make the user experience way better. There is no need for intrusive frameworks that tell us exactly all the layers to be used and how. Everything is ready to craft the code to make it express as much human knowledge as possible.

So we are taking the chance.

No need for MVC frameworks

In the first two weeks of the project we started using Backbone. In the first spike, we used the whole framework. A bit later, just the models and collections. Nowdays, we have completely got rid of it. It is a great framework, but we don't need MVC frameworks anymore on the client side because they are more restrictive than we need. We don't develop "screens", we try to create "smart components" that can be reused and provide a different level of abstraction. The screen is just a place holder for components that can be injected. With the rich UI programming that Javascript give us today, the paradigm has changed. It is time to retrieve practices from 15 years ago mixed with best practices learned in the latest years. I wouldn't port or copy exactly what we have been doing recently.


RS: enfocados hacia la calidad

Este post de retrospectiva vale por las últimas semanas. Desde el último post de retrospectiva hasta ahora, estamos notando una evolución espectacular en el equipo, tanto en el compromiso que cada uno demuestra escribiendo código de calidad como en la responsabilidad de completar las releases semanales. En la pizarra que usamos en la última reunión de retrospectiva aparecieron más anotaciones positivas que anotaciones de mejora 🙂  Sin embargo en este post voy a resaltar lo que queremos lograr.

La cuestión es no parar aquí porque sigue quedando muchisimo camino por recorrer. Simplemente seguir trabajando duro con ayuda de esta sensación de progreso que va calando en el equipo.

Lo que queremos hacer:

  • Los commits aún más cortos y legibles (tengo pendiente un artículo sobre esto que saldrá en la proxima tirada de Evitar que los commits lleven diferencias en tabulaciones y espacios para que no se registren cambios que no son de verdad en código sino en configuración del editor de texto.
  • Un branch por feature: tenemos que quitarnos de encima el agobio de que el dia de la subida de versión el branch principal no acaba de estar fino para mezclarlo con estable. Al empezar una nueva funcionalidad iniciaremos un nuevo branch. Cuando se toca código cómun se mezclará con la rama principal y se compartirá para que los demás tengan el cambio disponible lo antes posible.
  • Acelerar la velocidad de nuestras máquinas. En compilar el proyecto (.sln) y lanzar los tests se iba un minuto en cada maquina. Insoportable e impracticable para hacer TDD. Hemos cambiado dos máquinas comprando todo el hardware nuevo, doblando la memoria RAM, y poniendo discos duros nuevos. También hemos optimizado la configuración de la compilación. Ahora se tardan 3 segundos en compilar y otros 3 en pasar los tests. Con eso recuperamos más que de sobra la inversión en hardware. Pero aún quedan varios compañeros con equipos lentos. Es muy importante resolverlo cuanto antes.
  • No hacer cambios en base de datos sin hablarlo primero con los demás y sin que sea totalmente inevitable. Nuestro objetivo es que la BD sea lo último que se toque, tratando de modelar primero el comportamiento en el código.
  • No olvidar pasar todos los tests despues de hacer "merge" y dar la voz de alarma cuando alguno se ha roto.
  • Mejorar el tiempo de respuesta de las incidencias.
  • Seguir formándonos, leyendo libros y practicando ejercicios. En la sesión formativa de los viernes y en casa.
  • Conocer más el código que hacen los demás y la funcionalidad para evitar duplicarla. Tener aún más cuidado en la code review de las mañanas.
  • Automatizar la generación de bases de datos de quita y pon, para pruebas de integración.
  • Cuando el código legado es abrumador, nos trazamos un mini "backlog" de los cambios que queremos conseguir hacerle y una estimacion de tiempos para irlo haciendo (ej: en 15 minutos, cambiar este método para que en lugar de recibir 7 parametros reciba un objeto).


  • Aumento de lo concienciado que está el equipo para escribir código más legible y mantenible para los compañeros.
  • Despliegues automáticos. Yeah!!
  • Estamos priorizando mejor. Nadie ha tenido que hacer ni una hora extra porque hemos afrontado a tiempo todas dificultades y la comunicación va mejorando.
  • El número de incidencias va descenciendo.
  • Se están haciendo más commits y más pushes (nos acercamos a la media de 3 commits por hora).
  • Se hace pair programming cuando es productivo y se programa por individual cuando la pareja se da cuenta que no se está aprovechando bien.

Don’t let mockito confuse you

The new version of mockito comes with a new method: spy. Very useful feature but... bad name!

The mockito's "mock" method creates already a spy object. The "spy" method creates a "proxy" or "proxy spy" object. Totally confusing, isn't it?

The "mock" method is not really awful, because you can also use the double as a mock or just a stub, and it is common to use the name "mock" for all kind of doubles, although still confusing. The benefit from naming the double properly is that it helps programming by intention, which is a big part of Test Driven Development.

I would rename "mock" to "double" and "spy" to "proxy". Anyway, don't forget that, when using the mockito's "spy" method any single call that you don't explicitly stub, will reach the actual object. It is really useful to work with legacy code, in fact, we implemented it in pyDoubles, but using the method "proxy_spy".

Just make sure you understand what kind of test double you use and why. That is what matters in the end 🙂