28
May
0

Do you want to be a CAT? (Certified Agile Tester)

Potsdam is beautiful specially in this time of the year, it's definitely a must see,  I am loving the place. However, I am not here for tourism reasons. I am attending a special training called "Train the trainers" for those professionals who want to be trainers in the Certified Agile Tester program. And it's not because I am going to be a trainer for the CAT, it's about other training program we are planning :-) but will talk about that in a future post.
This is the first training for testers I attend to and I am really enjoying it. Half the training is about agile. The contents are very well prepared and so the teacher. So I can tell that in this training, people learn a lot and have to study and participate a lot. Not everyone passes the exam.

In this edition there are participants from 6 different countries or so and the atmosphere is great. One of my colleagues comes from Mexico, what a long trip!

The exercise I've enjoyed the most so far is the Lego game. Building a city "the agile way". You can find all the pictures here.

And there it is the short retrospective with lessons learned from the game in our small team:

  • We didn't ask enough to the product owner in the first iteration (acceptance criteria).
  • We didn't agree on some criteria or conventions even between us.
  • We didn't do any spike to have at least a rough idea of what a story point represented.
  • We committed ourselves with a bunch of user stories for the first sprint without any clue of how much does it take to build a single house and without any acceptance criteria for it.
  • Although I didn't feel any good at the beginning of the first sprint, with all those questions on my head, I couldn't prevent my 3 team mates from start building like crazy. Uncomfortable situation for me... I felt we were going to crash but couldn't avoided, we just crashed like dummies. Fortunately we did way better the next iteration so experiencing the failure was positive and maybe necessary for us to react and improve  :-)
This game, along with the marshmallow challenge are my two favorite metaphors to introducing agile in the small.
Best look to all the trainers that are going to do the exam on Friday!
18
May
0

The best coding dojo ever

 


I've got goosebumps on my arms most of the day. And it doesn't happen very often. This is the most emotional coding dojo I've ever facilitated. It's been in Gran Canaria, at the Universidad de Las Palmas de Gran Canaria (EII ULPGC).

The last day in college for some students, where many of them were thinking of their uncertain near future. Asking for recommendations and expressing many doubts.

More than 50 people coding together for more than 8 hours, in an incredible atmosphere.

 

 

How did we get here?

There is only one book on TDD in Spanish so far. Published by my friends and me back in 2010, under the creative commons license. Creative commons is like a virus for this. One year ago a real master, Jose Juan Hernandez (@jjhernandez) decided the book was nice to teach his students how to write clean code. We didn't know each other. In fact I didn't know the book was being used at the University. Jose Juan has been coding since 1985 and I do believe he is a software craftsman, now that I've seen him coding and teaching.
A couple of months ago he contacted me  see if I could give a talk to his students, about TDD in the real world™ and the encounter was excellent. The coding dojo proposal came along right after that.

Why has it been so good?

Guillermo and I

Several factors in here. Jose Juan has been teaching TDD, Refactoring, Patterns and Clean Code to his students the whole year. No only the practices but the values. This is the reason we believe he is a master, because his students have embraced and internalized his values and principles.

  1. So about 30% of the students were familiar with the techniques, and we asked them to pair up with those not exposed to automated tests and example driven design before. And they explained everything to others with passion. 
  2. In a regular coding dojo the facilitator does not necessarily teach. Her goal is facilitating. In this case though, we've been teaching people, so it's been half of a training session. With direct feedback on their work, based on our experience.
  3. We were 3 guys facilitating: Guillermo Pascual (@pasku1), Jose Juan and me. And the sinergy it's been huge.
  4. Everyone was absolutely willing to learn and share. Passionate people, warm and friendly.
  5. It's been a total win-win event. We (facilitators) have felt very useful and appreciated, it's been fulfilling. Some people have discovered a new way of understanding their careers, and what "caring about code" means.
  6. The retrospectives following every iteration were very participative, people were able to discuss among them.
 

Jose Juan

What's next?

  • This is a milestone in the Canary Islands software development community, I can feel it. Something is changing...
  • Let's keep on practising together. The AgileCanarias community is growing and it's a good starting point  o meet new people and learn new stuff. The Tenerife group is kind of mature and stable now, let's do the same in Gran Canaria. And let's join the two groups for dojos and local conferences.
  • We have the Agile Open Space this year in Tenerife. Join us, it's a great opportunity to discover more.
  • Now you know there are different ways of writing software. Keep on learning, it's a never ending path.
  • When is the next coding dojo, who will organize and facilitate it? :-)

I want to facilitate a dojo, what should I know?

  • Manage people's expectations. In general a coding dojo is not a training session. Be honest with participants and help beginners as much as you can. Otherwise they'll be scared, run away and take a wrong idea about what it is.
  • A dojo is a space for innovation, try different things all the time, you don't have to follow the manual on the go. Just use your imagination and empathy.
  • Ask someone experienced to facilitate it before doing it yourself, if possible.
  • There is an interesting new book on this by Emily Bachehttps://leanpub.com/codingdojohandbook (haven't read it yet), foreword by Uncle Bob Martin.
  • Check out this video by Emily Bache: http://www.youtube.com/watch?v=yao5XLJqogQ

Acknowledgments

  • Jose Juan and Guillermo Pascual.
  • All the participants, of course. Without them, there is nothing to do.
  • Jorge Castellano for his pictures and video. Pictures will be uploaded soon here. Jorge already uploaded some pictures to twitter. Just search for the hashtag #dojoULPGC
  • Fran Santanta for his support and organization. Fran brought journalists from local newspapers and TV, apart from the food and everything else.
  • Mario Hernandez Tejera for his company, hospitality and sharing his interesting/wise thoughts.
  • All the colleagues who work with Jose Juan for his support and energy.
  • JM Beas, Xavi Gost and other folks from Agile Spain, as they introduced me to coding dojos.

This is the related thread in the AgileCanarias mailing list.

fotos de Jorge Castellano
Guillermo Pascual y Carlos Ble
 

 

 

1
May
0

Programming through VNC

TightVNC settings

I connect to my desktop PC (which is very powerful) from my laptop (very old), when I feel like coding from the other room, the couch or the bed. Desktop is a Windows 7 machine, laptop is Ubuntu. I have installed TightVNC on the Windows machine and SSVNC (without any SSL) package on Ubuntu. Everything was fine but still, the cursor was moving so slow through the source code.

The key is the "Screen pooling cycle" option on the TightVNC configuracion. It's default value is 1000 but changing it to 100, makes me feel like I am coding in my desktop PC.

This is obviously in my LAN, through the internet it's better to use Teamviewer or Chrome Remote Desktop. And if you can work only with a terminal, then SSH+ Tmux is the best choice.

Happy couch coding!

 

7
Apr
0

Add the feature where you would like to find it

A new change or feature is about to be implemented. There are several places where it can fit in, and all of them seem to respect the Single Responsibility Principle. My tendency used to be adding the new feature where it was easier to place.  However now I consider other criterion. I ask myself this: If I need to navigate through the code base a bunch of months later to read the feature implementation... where would I look at in the first place?

Lesson: once you make sure your code is going to be SOLID, add the new feature in the place readers would expect to find it.

7
Apr
0

What methods should Value Objects contain?

Value objects can contain methods. Otherwise they are just anemic models. Those methods prevent the feature envy code smell and ease refactoring. They manipulate object internals promoting cohesion and low coupling. But don't forget about the Open/Closed principle. If you add that method to the object, is the code still open to extension without modification?

Imagine a value object encapsulating a collection. Now you need a method to sort the items in the collection. Should the "sort" method be part of the collection object? If is there a way to change the sorting algorithm without code modification, then the answer is yes. Otherwise the answer is no. Move the "sort" method to a specific class whose responsibility is sorting.

7
Apr
0

What would you expect the code to do?

Writing quality code is about satisfying the expectations of the reader. And the reader might be yourself a couple of months later.

Let me tell you a mistake a made recently. I was test-driving a few classes and one collaborator was a stack. But I only needed the stack to give me the last two items pushed on top of it.  So I ended up with a function like this:

function pop(numberOfItems){
   // ... some code dealing with border cases...
   // and the happy path:
   return [items[len -1], items[len -2]];
}

And everything went well. The stack was good enough for the object using it.
After a few months I needed to use the stack again but I forgot about its internals. I was writing some tests for a new class also depending on a stack. As the stack was already tested, I stubbed out the "pop" method in the new test pretending it could give me the last 3 items on the stack. The unit tests passed and my new class was working fine with the stack. However, it didn't work into production. Lesson:
Although TDD encourages you write only the smallest amount of code necessary to make the test pass, you should implement all the behavior a method is expected to have when someone reads its signature.

In one way or another I was coupling the stack to the class using it. But APIs should always tell the truth. Classes and methods should do what their name say without the need to know how other artifacts consume them.

 

7
Apr
0

Careful with JavaScript object literals

JavaScript object literals are very handy, they are just key-value pairs. Very convenient to implement dictionaries and also a very simple implementation of the Singleton pattern:

var message = {sender: 'bob', body: 'hello'};

Duck typing is a technique I use very often as I test-drive my JavaScript code and object literals make it very easy. But overusing them lead to several problems:

I am no longer using object literals in my tests because when I need to add methods to those objects, I need to change too many tests. Also, exposing all those fields lead to feature envy rapidly, producing semantic coupling sooner or later. Although tests are written fast with object literals, I prefer to encapsulate the fields into business objects.

 
function Message(sender, body){
   this.sender = sender;
   this.body = body;
}
var message = new Message();
 
5
Apr
0

Push the “how” down: Cukeup! 2013

It's been my first time attending to an event at Skills Matter and it's been awesome :-D

Cukeup! is the annual conference about BDD and Cucumber. This was the third edition.  Let me share with you the ideas I listened yesterday. The ideas and sentences written in here are not necessarily what speakers said, this is just my understanding of them. You can now view the talks online from the SkillsMatter site.

- Keynote by Aslak Hellesøy - father of Cucumber and coauthor of the excellent Cucumber book (which I recommend) and Cucumber Recipes (brand new):
Aslak told us how the development of Cucumber is going and the new design ideas they are working on, together with a review of the many flavors Cucumber's got. I missed a reference to SpecFlow in the slides though, as it is one of the tools I use and I think Gaspar Nagy is doing a great job (and he came to the conference by the way, which was nice). The thing I liked the most from this keynote was that he announced their new book recently published, Cucumber Recipes, which is now on top of my wishlist. And also the honest way he talked about the architecture redesign Cucumber needs and how are they approaching it. This is a good example of why architecture and design are so important.

- One-line step definitions with Matt Wynne - coauthor of the two books mentioned before:
You can see the talk online here (and so the others too). Having read his first book, the new ideas I got from this insightful talk was that the popular test pyramid can be "rotated". Matt and Seb Rose came across this idea together. Basically, you can use Cucumber to describe features without the need to access the application end to end, just exercising low level classes and methods from the step definitions. In those cases Seb decorates the features with tags indicating the level of abstraction they belong in (@without_ui for example). If you haven't read Matt's book, this talk is a good summary of some parts, it features some of the most important values and principles. Remarkable ideas:
Push the "how" down because it changes often and because it will not bring people into BDD as the features written in the imperative way are hard to understand and boring, cluttered with irrelevant information. Sometimes imperative style is the result of ignorance but it can also spot lack of trust in the team.  And... don't nest steps (call another step from the step definition).

- Working in the Cucumber World with Andrew Premdas:
Andrew's advise is to benefit from both, natural and programming languages when we write features and their step definitions. In order to do that, the "World" (fixtures used within step definitions) must be expressive, self-descriptiveAlthough he discouraged us from using global variables, there are some exceptions, something useful when referring to oneself in the fixtures is to use the variable "I" (@I in Ruby). Enrique Comba also suggested using @narrator (@ comes from Ruby) as the variable used to refer to the person telling the story. Because "narrator" might be clearer than "I" when there are many steps. Andrew said it was his first talk and he did very well in my opinion because clearly his primary concern was to communicate, so the message came out effectively.

- Don't you trust me? with Seb Rose:
Trust is easier to loose than to win. When developers tell testers that everything is fine but then it breaks, they are loosing points. Same when developers don't allow testers to navigate through the code base. Testers can work more effectively if they know a bit of programming and are able to check out the source code for inspection. When team members trust each other they clean up the road for others. Documenting high level architecture and components also helps.
Then he explained an experiment he is trying out: end to end tests are good to win trust so he starts by exercising the application like that from the features. But after that, he considers whether end to end is really the right way to go, because maybe exercising low level methods rather than several layers is cheaper, as long as there are already other end to end tests covering the path. Again, the rotated pyramid.

- The Impersonator Pattern with Enrique Comba:
Enrique got many of us thinking how to leverage the pattern right after his talk. He explained it on his blog time ago. A very nice secondary effect of this pattern, is that one can rapidly review the implementation of the impersonators and get a summary of what every persona in the project can do and what can't do. Useful documentation to have, specially when you have hundreds of features and thousands of steps. It was definitely a great talk, source of inspiration. His craftsman spirit lead him to this pattern as the consequence of following the "maximize code clarity" principle.

- Hands-on Cucumber.js with Julien Biezemans and Matt Wynne:
Julien, the creator or Cucumber's JavaScript flavor was pairing up with Matt to test-drive a little game live, writing the code directly in the browser with particular web environment set up by him. I am already using Cucumber.js so nothing new about that but I didn't know about uitest.js which they were using during the session. I am actually doing something similar on my own with Jasmine to run the app within an iframe so is good to know that more people are doing that. Some other times I just run cucumber.js from the command line using zombie.js.

 - Cross-platform BDD for Mobile with Karl Krukow:
Karl showed Calabash, a very powerful framework for mobile testing. Really impressive to me. It fits perfectly with hexagonal architecture and helps to avoid duplication in the tests while testing native apps on different mobiles platforms. It's really worth having a look at Calabash. I'll definitely will do. Of course the integration with Cucumber is excellent.

- Testing web apps with Cucumber.js with Paul Jensen:
Good speaker, nice technical stack and good ideas from the talk. He showed code from his successful app Dashku and its tests. I must say that the way I write JavaScript apps is different specially because I test-drive them whereas he showed a prototype developed without tests, having them added afterwards. But still, some good points in the talk.

Now I'll watch all the sessions that I couldn't attend to (haven't found the way to split myself in two). 

See you next year hopefully!

22
Mar
2

Unit testing JavaScript with Promises and Jasmine

Promises are a nice solution to write readable asynchronous code in JavaScript. If you understand Spanish, I highly recommend this great talk on Promises by Enrique Amodeo.

But, is the code with promises easy to unit test? It's not very difficult, you have to take into account the calls are asynchronous even if the production code executes instantly.

Here is some code I've written using when.js library:

 
function TicketSalesService(){
  var self = this;
  // ... some other code over here...
  this.buyTickets = function(quantity) {
     purchaseOrder.quantity = quantity;
     // THIS IS THE CODE WITH PROMISES:
     this.server.isUserRegistered(user)
       .then(tryToBuyTickets)
       .then(informSubscribersAboutPurchaseResult)
       .otherwise(function (err) {
           helpers.registerPromiseError(self, err);
       });
   };
   var tryToBuyTickets = function (response) {
       if (!response.registered){
          self.onRegistrationRequired(); // trigger event
          throw helpers.endOfPromiseChain; // stop the chain
       }
       return self.server.buyTickets(purchaseOrder);
   };
   var informSubscribersAboutPurchaseResult = function (response) {
        if (response.success)
            self.onPurchaseSuccess();
        else
            self.onPurchaseFailure(response.message);
   };
   this.onRegistrationRequired = function() {/* event */};
   this.onPurchaseSuccess = function() {/* event */};
   this.onPurchaseFailure = function() {/* event */};
  // ... some other code over here....
};
 

In this code there is a helper namespace providing a function and a constant:

 
helpers.endOfPromiseChain; // this is just a constant, a string.
// And this is a function to ease testing:
helpers.registerPromiseError = function (target, err) {
    if (err != helpers.endOfPromiseChain){
            target.errorInPromise = err.toString();
    }
};
 

The "server" dependency in the TicketSalesService is just a jQuery ajax wrapper. There is a rule in TDD that says, "do not mock artifacts you don't own". What I do is wrap up jQuery.ajax so that I can easily stub out the server response and also change jQuery for other library if I needed to.

 
Service.prototype.isUserRegistered = function (user) {
    var deferred = when.defer();
    // wrapping jQuery aja:
    this.requestData("theUrl/goes/over/here",
	{ data: user },
	function(data) { // jQuery.ajax success invokes this
	  deferred.resolve(data);
        });
        // TODO. call deferred.reject(); on error
    return deferred.promise;
};
 

What about the tests? I am using Jasmine as the testing framework. I test-drove the code above and these are the resulting tests:

 
it("triggers event when server responds that the user is not registered",
function () {
    stubServerResponse(salesService.server, { registered: false });
    var promiseSpy = spyReturningPromise(salesService,
                            "onRegistrationRequired");
 
    salesService.buyTickets(5);
 
    assertAsyncExpects(promiseSpy, salesService);
});
 
it("tries to buy when server responds that the user is registered",
function () {
    stubServerResponse(salesService.server, { registered: true });
    var promiseSpy = spyReturningPromise(salesService.server,
                                              "buyTickets");
 
    salesService.buyTickets(5);
 
    assertAsyncExpects(promiseSpy, salesService);
});
 
it("triggers event when tickets are purchased",
function () {
   stubServerResponse(salesService.server,
                 {success: true, registered: true});
   var promiseSpy = spyReturningPromise(salesService,
                               "onPurchaseSuccess");
 
   salesService.buyTickets(5);
 
   assertAsyncExpects(promiseSpy, salesService);
});
 
it("triggers event when prescriptions could not be purchased",
function () {
    stubServerResponse(salesService.server,
           {success: false, registered: true, message: 'fatal'});
    var promiseSpy = spyReturningPromise(salesService,
                                "onPurchaseFailure");
 
    salesService.buyTickets(5);
 
    assertAsyncExpects(promiseSpy, salesService);
});
 

My code is using DOM Level 0 event handling. You can read more about event driven design in this former post.
The tests are very clean if you are familiar with Jasmine spies.
The method "stubServerResponse" replaces the function "requestData" in my "server" object to simulate data coming from the server.
The other helpers are here:

 
var assertAsyncExpects =
function(promiseSpy, target, additionalExpectation) {
  waitsFor(function () {
    return promiseSpy.called ||
       target.errorInPromise; }, 50
  );
  runs(function () {
      // this tells me if there was any unhandled exception:
      expect(target.errorInPromise).not.toBeDefined();
      // this asks the spy if everything was as expected:
      expect(promiseSpy.target[promiseSpy.methodName]
           ).toHaveBeenCalled();
      // optional expectations:
      if (additionalExpectation)
            additionalExpectation();
  });
};
 
var spyReturningPromise =
function(target, methodName) {
    var spyObj = {called: false,
                  target: target,
                  methodName: methodName};
    spyOn(target, methodName).andCallFake(function () {
        spyObj.called = true;
        return when.defer().promise;
    });
    return spyObj;
}
 

These two are basically wrappers around Jasmine to remove noise from my tests. The funcionts "waitsFor", "runs" and "spyOn", belong to Jasmine. The first two deal with asynchronous execution whereas the third one creates a test double, a spy object.

What are the tricky parts?

When there is an exception inside the "then" or "otherwise" functions, it is captured by the promise and the test doesn't know anything about it. So when the test fails, it might not be for an obvious reason, and I want my unit tests to tell me where the problem is very fast. So I create a property in the object containing the "then" methods, called "errorInPromise" that I can check later in my tests. I add the "otherwise" handler at the end of the "then" blocks to ensure any exception thrown within them is captured and can be read in the tests.

What do you do to unit test your "promising code"?

17
Mar
0

Segunda edición del PMA

Foto de grupo

Acabo de regresar de impartir mi clase sobre Clean Code y TDD en el Postgrado de Métodos Ágiles de La Salle (#PMA), en Barcelona. Se trata de la segunda edición de este postgrado único en el mundo.

La experiencia ha sido muy positiva e intensa al igual que lo fue el año pasado. Los participantes son profesionales del sector con un interés enorme en el postgrado así que funciona de maravilla.

Nuestro primer test en verde

Si viviese en Barcelona o en algún punto cercano, sin duda me inscribiría como alumno para la siguiente edición del postgrado por la increible selección de profesores con que cuenta. El temario toca absolutamente todos los puntos clave de las metodologías ágiles, desde las personas hasta el código.

Este año había varios gestores de proyecto y tambien DevOps entre los asistentes. Llevaban muchos años sin programar y a pesar de ello han puesto muchas ganas para aprender en este módulo en que hablamos sobre todo de código. De cómo escribir código para las personas, no para las máquinas. Poder hablar del cuidado con el que hay que programar, a personas que están en la gestión de proyectos, es motivador para mi porque pueden valorar mejor el trabajo que hace el equipo de desarrollo (y también las chapuzas que pueden llegar a hacer). Para mí es una oportunidad de dar a conocer lo importante que es la carrera técnica y la forma de programar y de mantener el código. En nuestro país los roles de desarrollador y tester están peor valorados que los roles no-técnicos, al menos en cuanto a salarios, por lo que los buenos programadores acaban por desaparecer al "promocionar" a puestos de gestión.

El postgrado proporciona una visión integral muy importante para impulsar el cambio hacia la calidad que necesitamos en estos momentos.

A continuación listo la bibliografía y demás recursos que comenté en clase:

Ha sido un placer, volveremos a vernos en el futuro :-)

Gracias a César Villar y Oriol del Barrio por las fotos.

 

Celadon theme by the Themes Boutique
teeth bleaching
baldness treatment