Archive for the ‘Software Development’ Category



18
May

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.

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.

 

 

 

 

1
May

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.

Happy couch coding!

 

7
Apr

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

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

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

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

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

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"?

13
Mar

Charla sobre agilidad, testing y TDD en la ULPG

Gracias a Jose Juan Hernández, profesor de ingeniería del software de la Escuela de Informática de la Universidad de Las Palmas de Gran Canaria, ayer 12 de marzo pudimos grabar la primera video conferencia con su clase. Hablamos de métodos ágiles, de testing y de TDD.

Tuve algunos problemas técnicos y no se si la parte de preguntas se grabó también. Pero seguramente no será la ultima colaboración porque ha sido muy enriquecedora para mí.

Muchas gracias a Jose Juan por hacerlo posible y a sus alumnos por el gran interes mostrado durante la sesión.
Esta es la primera noticia que tengo de que nuestro libro de TDD se esté usando como material docente en la Universidad. Es una gran noticia y me anima a publicar una nueva version mejorada.

14
Feb

Share what you learn, to learn even more

I always encourage developers to write a technical blog. I've already convinced some of them to start blogging... yeah!

Why is it that you explain your problem to other person (or even to a rubber duck) and you find the solution yourself as you describe the problem? The brain works differently when you think without talking loudly, than when you talk or write.

There are different learning levels for techniques:

  1.  You discover there is something new you want to learn.
  2.  You start reading how others use the technique but don't understand what they are doing. It's confusing at first.
  3.  You start reading how others apply the technique and you understand what they do, but you can't do it yourself.
  4.  You are able to start doing it by yourself.
  5.  You explain what you know to others and then new doubts and thoughts pop up, and you get a deeper knowledge.
  6.  You teach people on the technique and that gets you closer to the master level. The more you teach the more you learn.
  7.  You eventually become a master.

Write a blog

Just do it for yourself, write notes that can be helpful for you in the future. Explain what you learn. It might help others and it will definitely help you, just for the sake of learning. Don't worry too much about your writing style, you are not writing a book and it is your blog, don't let the wording stop you from your willingness to share. In my case, every time I write in English, I learn more English also, so it is not only technical stuff that I learn. However, I prefer to write it even feeling that I am making some grammar mistakes, rather than keeping the draft for months, waiting for the perfect moment to polish my writing to come off. I try to deliver frequently and learn from my mistakes. All I know is reading my post when I finish it to fix the mistakes I notice.

Talk to others

Don't miss the opportunity to expose what you learn in your local community. Talk to others and present papers for conferences. But if you decide to talk in a conference,  prepare your pitch upfront. Prepare your slides and your talk very well before doing it. The more you practice your pitch the more you will learn and the better it will be for the audience. Don't be afraid when talking for a big audience, nobody is better or worse than you, you deserve all the respect, and so your audience.

Teach what you know

If you don't want to feel uncomfortable as the questions come in, you better know what you are talking about. This means you have to prepare the classes very well, and that will help you to know the technique really well. Teaching is a great motivation to learn. If you don't have experience as a teacher, my advise is to teach your friends or colleagues in your local community for free, until you reach the point where others confirm you they are taking value from your lessons.

I hope to inspire more developers to, at least, start a weblog :-)

 

 

 

Celadon theme by the Themes Boutique
teeth bleaching
baldness treatment