Carlos Ble

Carlos Ble

I am a professional software developer, I solve problems.

I also teach and mentor developers to build better software.

Developing software since 2001.

Can I help you?

  • Do you need high quality tailor-made software?
  • Need training on TDD, clean code or refactoring?
  • Do you need a technical consultant?
  • May I pair with you to write better code?

Events

Upcoming training courses:

  1. TDD - [en Español] - 6 y 7 Octubre
    Gran Canaria
  2. TDD - [in English] - October 20, 21 & 22
    London, UK
  3. TDD - [en Español] - 29, 30 y 31 de Octubre.
    Madrid, Spain

Conferences:

  1. I'll be at the Agile Testing Days 2014
  2. I'll be at the London Test Gathering Workshops.

With good names for packages, classes, methods, variables,... code should be self-explanatory.  Long method names are not a problem if they really make code read better and don't reveal too much implementation details. Names are more powerful than most developers usually think, they have a profound impact on our designs. In general names should be pronounceable but there are always exceptions.

  • In a small loop, it's OK to name the index i, j, k or something like that you don't have to say theLoopIndexWhatever. In fact, "i" reads better in a short loop.
  • Methods should not contain concrete details, those should be parameters instead:     

            assertThatThereAreTwoResults(results)

          Should better be written like:

                      assertThatThereAre(2, results)

  • Method names should say what they do, but not how:

            addWordIfIsValidAndHasCorrectLength(word,  results)

          Should may be:

                     addValid(word, toResults);

  • The name of the class should be considered when naming methods. The name of the methods should be considered when naming its arguments. Given that methods should not have more than 3 parameters (the less the better), the names of the arguments may be combined with the name of the method, specially if there is a single parameter. Good names care about their context.

            result = expressionResolver.resolveExpression(expression)

          Reads better like this:

                     result = resolver.process(expression)

  • In the case of test methods, the name should describe the behavior without concrete details. The details are inside method body. The test method name is the description and the body is the example:

            one_plus_two_returns_three()
          Should be:

                     sums_two_single_digit_numbers()

  • Names should not contain technical details, like the types , because they are an excuse not to search for proper domain names. Modern IDEs provide enough help for the programmer to find out types, code should be business domain oriented.

            parseString(expression)
          Should be:

                     parse(expression)

Avoid prefixes and suffixes like "Abstract*", "I*" (ISomething), "*Impl"...

Don't let the syntactic noise bother you when choosing your names, the fact that there is a brace in the middle should not impede you from writing a line of code that reads like well-written prose ;-)

I'll probably will go on updating this post with more examples.

 

I am using LeanPub to create some manuals and it's a very nice service.  You just have to use Markdown to write your document and it generates a good looking pdf document from it. Well, as far as I've read today it's actually kramdown a superset written in Ruby. Everything was fine but that my partners wanted to add a custom header image in the manual. This is not supported by Leanpub, in fact it's not supported by Markdown as far as I know. So I decided to manipulate the pdf using my preferred OS (linux). It's not easy!

Pdftk (the pdf toolkit) is great!

pdftk  it's a powerful command line tool to manipulate pdfs. The tool that has saved me eventually. Thanks Sid Steward! What I've done is:

  1. Use LibreOffice to insert the header image into an empty document and then save it as pdf (header.pdf)
  2. Use LibreOffice to create a cover for the book (cover.pdf)
  3. Remove the first two pages from my_book.pdf,  generated by Leanpub:
    pdftk my_book.pdf cat 3-end output tmp.pdf
  4. Add the cover:
    pdftk cover.pdf tmp.pdf cat output tmp2.pdf
  5. Add the background:
    pdftk tmp2.pdf background header.pdf output my_final_book.pdf

See more powerful examples of pdftk.

Things that didn't work so well:

  • Xournal: this tool is great when it comes to adding some text to a pdf document among other things. Probably the best pdf tool with GUI I've tried. However, it doesn't support adding images or headers. There is a patch to insert images but I didn't spend the time trying to compile it.
  • PDFedit: looks powerful but I didn't know how to use it. I could remove text from the document easily but nothing more.
  • uPDF: looks interesting but it's buggy,  like experimental. It didn't work for me, freezes when saving the document and the GUI is quite hard.
  • PDF Mod: this one is looking very good! but I knew about it when I already solved the problem and didn't try it out.  The doc says it modifies pdf but I don't know whether it supports headers/backgrounds and things like that.
  • LibreOffice-pdfimport: Right, it opens up the pdf document but it looses its format and images at least for my pdf book.
  • Pandoc: In desperation I tried to generate the pdf myself skipping Leanpub, from the markdown text. Pandoc is brilliant and very powerful converter. Together with latex-beamer it has generated a pdf for me:
    pandoc -t beamer -o my_book.pdf -i my_book.txt
    The problem was that I don't have a nice latex template to use so I just loose all the nice formatting provided by Leanpub.

I also tried two commercial tools for Windows but none of them were very good either.  The prices were reasonable so I though I would just buy them but the trial version was good enough to realize the software wasn't good.

This story has taken me way much time I thought,  I hope you save some time reading this if you face the same problem :-)

 

iSQI logo

I am happy to announce that the work  I've been doing in the last quarter in collaboration with iSQI is now official. We have prepared a new TDD training based on the successful course that I've been running in Spain for about 3 years. The new training is now part of iSQI's Certified Agile program, so those who want to take the exam after the course will become certified (if they pass it).

iSQI is a well-known organization in Europe specially among testers. Their CAT (Certified Agile Tester) is quite popular and I can tell is a good training because I participated in one edition just to see how they work. Now iSQI also wants to provide more training options for developers.

I've created a hand book for the participants and a guide for trainers, updating my original course with an additional day and new exercises.  In January I'll be in Berlin running the first Train the Trainers (TTT) where developers passing the exam will become trainers entitled to run official courses and certify other developers.

I do know this training provides great value to developers. I encourage people new to TDD to participate in the training because I know they will learn. I would discourage those who want just the certification because this one is not easy to get.  The exam is mostly coding to demonstrate that candidates really understand TDD. Last month we had the first pilot training in Potsdam (Berlin) and only half the participants passed the exam.  Fortunately all of them learned something new and I can tell that if they keep practicing, they will pass the exam in a few months. But at the same time I am satisfied that not everybody passed the exam because we had some people that haven't been coding in the recent years and I felt they were not ready yet.

I don't know about other certifications because I don't have any, and the value of this training is not in the certification either but in the important lessons participants learn. However I can confirm that the people passing this exam will know what TDD is, and what it's not and that provides value too. We are doing a good job there.

My challenge now is to train other trainers so that we preserve the essence of the course adding even more value and quality.  If you are a seasoned test-driven developer please join us as a trainer :-)

We know TDD is not mainstream and will probably never be, but I see in this a great opportunity for TDD to reach more developers. An opportunity for developers to feel comfortable asking their managers for three days to come and practice and then keep on practicing on a regular basis.

Even though the title of the training is TDD, we cover some basics on clean code and SOLID design principles to make sure we triangulate towards well-designed code. The emphasis is on good naming and removing duplication. The first day is all about refactoring, unit tests, and design principles.

For my friends in Spain I have to say that we would like to translate the materials to Spanish and run a TTT somewhere in Spain and also in Latinamerica. Probably in Mexico and Colombia. But we don't know when is this going to happen or whether it will happen eventually. For now, all is in English and the first editions will happen in Berlin. But if I can give the course with my bad English, you can for sure participate ;-)

All the information and contents about this training is here.

 

 

My experience at the IronHack

 

I am one of the lecturers/mentors of the first IronHack edition, a training program for people who want to become professional developers. My part takes only three days and it's been this week. Three full-day hands-on sessions on JavaScript, TDD and testing techniques. The experience has been fantastic for me.

ironHack

During the class at IronHack

When I knew about this idea of training people with any background so that they become developers in only 8 weeks, I thought... shit man, how the hell are people going to learn and assimilate all the contents and concepts in such a short period of time? That's impossible! But I was invited as a mentor by Mauricio Morales and his energizing message made think that I wanted to know how this accelerated training academies works. So I accepted the invite to experience something new, to experiment and learn. And it's been totally worth joining the teachers team :-)

The best thing it's been getting to know the people. IronHack staff are great guys and the participants/students are brilliant. They are doing their best to understand all these new techniques and tools despite of their different backgrounds. People that progress faster take their time to pair up with the people that are struggling, helping them speed up the pace and learn. The people with less programming background are very patient and motivated. Well, all of them are very motivated, this is what is exciting in there.

For me it's been a challenge because I am used to train developers but not beginners. Some of the folks were developers but some of them were pretty new to software development.  And difficulties is what make me learn the most, so I've learnt important lessons that will help me out in the near future. Anyway I am quite satisfied with my work and specially with their effort.

Now, as you may imagine, this training does not entitle all the students to consider themselves senior software developers right after the end of it, it's just too short! But I don't think that is the objective. They are learning from passionate professionals that work every day in "the real world". One or two different guys like me every week. They are getting to know the best techniques we know, how we think and work so that they are learning from our mistakes. What has taken years for some of us is summarized in hours during the training. Internalizing them is going to take sometime to students but it's still faster than some traditional training methods.

I believe this concept is good even if it only serves to add some pressure on other training methods. We need better developers and providing different training alternatives sounds right to me.

If in the future I meet a single person from this fantastic group and she tells me that what we practiced in the class was  useful in her career, then my objective will be accomplished. If they write code with care from now, I'll be totally satisfied. Code for other human beings, not for machines which is what some people believe after other training programs.

I want to say  THANK YOU to the guys behind IronHach: Ariel Quinones, Gonzalo Manrique, Israel Guitierrez, Xavi Leal, Mauricio Morales and company.

And of course THANK YOU to the intrepid participants: Sergio Revilla, Daniel Bardaji, Daniel Castillo, Agustin de la Villa, Alejandro Dominguez, Daniel Cusan, Marta Fonda, Fernando Moreno, Ruben Kanna, Imanol Yañez y Jaime Muñoz.

 

 

2013-11-27 17.58.59

Tuenti office with my friends: Miguel Angel Garcia, Joaquin Engelmo, David Santiago, Imanol Yañez and Marta Fonda

And I visited Tuenti for my first time, finally!

Yesterday was a very intense day because right after the full-day session at the IronHack, I went to Tuenti offices (Madrid) to give a talk to software engineers.  Last week my good friend Kini and Jose Lorenzo sent my an email inviting me to do so. I didn't prepare slides because I didn't feel like giving another talk with slides I felt more like having a discussion. I just prepared a few ideas based on my experience and my point of view to start up the discussion. It was along the lines of professionalism, XP and specially practices like TDD and BDD. Fortunately people were participating in the discussion with a lot of interest. I am not very good at counting but I guess there were more than 50 people. Tuenti gathers some of the most talented developers in the country, not only Spanish developer but also from other countries.  It's a very nice place, looks  very cool as a place to work. I've been listening how good people are in Tuenti for a long time so I am glad I got to know people in person that I only knew from twitter and really enjoyed sharing experiences with them. I hope to meet this group more times in the future.

Mock objects on JavaScript

Many frameworks use the word "mock" for what in reality are "spies". But that's OK, the work "mock" in English covers actually all the possible test double types...

However according to G. Meszaros, a mock object is a specific type of test double that is configured with expectations before exercising the system under test. During the execution the mock compares the calls being made, to its expectations failing if they don't match.

The two frameworks I use for test doubles in JavaScript are Jasmine and Sinon.js. And I also use some helpers of my own. None of these two frameworks provide actual mock objects. Sinon has a "mock" function that let us configure expectations before exercising the system under test. It behaves like a mock if we are working with functions only. Nonetheless if we are working with objects (OOP), then what Sinon provides is not a mock object because a call to any other method in the object other than the expected, will not fail the test. And it should as unexpected calls should make the test fail.

The solution to have real mock objects with Sinon is just a little helper:

  1.  
  2. //------ HELPER FUNCTIONS
  3. function unexpectedCall(functName)
  4. {
  5. return function(){
  6. throw new Error('Function ' + functName + ' was not expected but invoked');
  7. };
  8. }
  9. function inocuousCall(){
  10. return function(){};
  11. }
  12. function replaceAll(obj){
  13. return {
  14. methodsWith: function(fn){
  15. for (var propName in obj)
  16. if (typeof(obj[propName]) == 'function')
  17. obj[propName] = fn(propName);
  18. }
  19. }
  20. }
  21. function stubThe(obj){
  22. replaceAll(obj).methodsWith(inocuousCall);
  23. }
  24. function mockThe(obj){
  25. replaceAll(obj).methodsWith(unexpectedCall);
  26. }
  27.  
  28. //------ THE TEST
  29.  
  30. it("stores the user when adding a new one", function(){
  31. // the DOC (depended-on component)
  32. var repo = userRepository();
  33. // the SUT (system under test) and dependency injection
  34. var service = userService(repo);
  35. // patching the DOC, making it a mock
  36. mockThe(repo);
  37. var mock = sinon.mock(repo);
  38. // configuring expectation:
  39. mock.expects("store").once();
  40.  
  41. // exercising the SUT
  42. service.add(new User({email: 'test@test.com'}));
  43.  
  44. // verifying configured expectations
  45. mock.verify();
  46. });
  47.  

In languages like Java or C#, test doubles frameworks create a replacement for all the methods in the target class/interface. In JavaScript however, frameworks replace single functions. For this reason it's possible to have the same object acting as the SUT and the double in a single test. But the fact it's possible doesn't mean it's right. Whenever you find yourself in a test using a double for some method and then invoking another method in the same object, think carefully whether the design is appropriate. That smell is usually pointing out that you should extract a new class and create a dependency between the old and the new, so that one acts as the double and the other as the SUT.

In general I prefer to wrap up system functions so that I can inject test doubles and test drive my designs easily. In general is not a good idea to mock objects you don't own. But this time I was doing some research, preparing one edition of my Online Training Class on Test Doubles and came across jMockit as a way to stub out System artifacts. jMockit is an isolation framework that I haven't tried before.

The idea is to stub the System.currentTimeMillis built-in function. I tried PowerMock but it didn't work for this particular case. PowerMock is brilliant for stubbing static methods and constructors as long as they are not part of the system. Very handy for legacy code.

  1.  
  2. // import mockit.*;
  3. public void simulateCurrentTime() {
  4. new Expectations() {
  5. @Mocked("currentTimeMillis") System mockedSystem;
  6. {
  7. System.currentTimeMillis();
  8. result = 123456L;
  9. }};
  10. }
  11.  

This is the method I had to invoke from within my JUnit test in order to stub out the function. It works! I have to say that it took me more than one hour to make it work because I couldn't find this in the documentation. I found several blog posts but they are old, the framework has changed since then. Eventually, a combination of information gathered from several posts yielded this working method.

Kids, don't do this at home!

If you want to know more, join the next edition of my training class ;-)

Methods should be short, from 1 to 7 lines of code, maximum 10 in some cases (with the exception of some algorithms). Because a method does just one thing its name should describe it precisely. But it should not contain implementation details (like data types). The name of the method is the "what" and the implementation is the "how". Try to avoid implementation details in the name.
When you find yourself using the words "and/or" in your methods names, consider that you might be exposing too many implementation details and try to search for a better name.

Sometimes, people new to this kind of modularity end up creating methods that are not necessary:

  1.  
  2. private boolean checkIfCharsAreEqual(char[] wordArray,int first_char, int second_char) {
  3. if (wordArray[first_char] != wordArray[second_char]){
  4. return false;
  5. }else{
  6. return true;
  7. }
  8. }
  9.  

This method does not add any clarity to the code. Moreover boolean methods can just return the condition:

  1.  
  2. private boolean checkIfCharsAreEqual(char[] wordArray,int first_char, int second_char) {
  3. return (wordArray[first_char] != wordArray[second_char]);
  4. }
  5.  

There is no need for the "if-else" block when the result of the condition is the return value of the function/method. Even after this change, the method does not make sense. Try to "inline" the method to see whether the code invoking it reads equally good.

When conditionals contains more than one boolean expression (using logic operators AND/OR) then I usually prefer to extract a method so that the reader doesn't have to think, just read and understand:

  1.  
  2. // before:
  3. if (someCondition(arg1) && !someOtherCondition(arg2))
  4.  
  5. // after:
  6. if (isSomeCaseWithProperName(arg1, arg2))
  7.  

When methods are boolean, try to name them so that they read well preceded by the "if" keyword. I like using the prefixes "is" and "are" or "areThere" for boolean methods operating on single variables and collections respectively.

When the new method is just an alias of another method, consider whether adding it adds any value in terms of readability:

  1.  
  2. result = someVar.toUpperCase(); // is good/clear enough
  3.  
  4. // Whilst this method does not make sense:
  5. public String convertToUpper(String input){
  6. return input.toUpperCase();
  7. }
  8.  
  9. // And this method does not bring value:
  10. private void addWordToList(List<String> palindromes, String word) {
  11. palindromes.add(wordToBeChecked);
  12. }
  13.  
  14. // And this method does not bring any value:
  15. public boolean stringContainsAtLeastOneSpace(String input) {
  16. if (input.contains(" ")){
  17. return true;
  18. }
  19. return false;
  20. }
  21.  

Also notice that the prefix "string" in the method name is redundant because the parameter is a string. In the case of methods with one or two arguments, consider using names for the arguments that read well together with the method name:

  1.  
  2. public User findBy(int phoneNumber){
  3. ...
  4. };
  5.  

I believe the idea of a single exit point for functions comes from the 70's. A function used to have only one exit point, a single return statement. I still see some developers doing this but it's not a good idea. As soon as you have found what you were looking for, just get out the function.

The old style:

  1.  
  2. public int someMethod(String input) {
  3. int code = 0;
  4. if (someCondition(input))
  5. code = 1;
  6. else if (someOtherCondition(input))
  7. code = 2
  8. return code;
  9. }
  10.  

Improved: returning the value as soon as it's found:

  1.  
  2. public int someMethod(String input) {
  3. if (someCondition(input))
  4. return 1;
  5. if (someOtherCondition(input))
  6. return 2;
  7. return 0;
  8. }
  9.  

The second example is not only shorter but also less exposed to defects. In the first example, if for some reason I forgot the "else" and the second condition applies, I'd be returning the wrong value.

The reasons to return as soon as possible are:

  • Code is usually more simple
  • The likelihood of future defects is lower

Case study: Audience Response

Wow, AgileTestingDays 2013 it's being awesome! I gave my talk today, a practical "live coding" session. Last week I created a real-time application to communicate with the audience so that when I am speaking they can tell me if they are understanding or if they want me to repeat ...
So we started off using this app on my session. Interestingly enough the session was about building the tool again. From Cucumber specifications, all the way down to the GUI and the hub (server).

You can find the actual code of the application here and more importantly, the process I followed to write it, because I checked-in the code on every green test so by looking at the diffs, you'll figure out how code evolved.
Unfortunately the wifi didn't work well so I couldn't really take advantage of the app. Next time I'll bring my own wireless router to create our private LAN.

In order to prepare the session, I rewrote part of the app again myself. In here you can find this second iteration, again with a test committed at a time. By looking at the commits you can follow part of what I did during my session. You can take the code and practice yourself from this particular commit, comparing your moves with mine ones to see what we can learn.

Find the business specifications of the app here and the step definitions (glue) in here.

Now, the session didn't go bad, but it didn't go as well as I'd like. I did quite bad with the timing.I would have needed 90 minutes rather than 45 to illustrate the process properly. When I was preparing the talk, I wrote the code on my own and it didn't take much time, but presenting it's a different story, I've learned that I need about twice as much time.

2013-10-31 01.24.06But I am satisfied because several people understood the process and got value from it. Next time I run this session, it will go much better. And you know what? I've been approved by The Code Cop! Look at this picture.

 

I'll be happy if you were attending the talk and can give me some feedback in the form of a comment in this blog. As a reward, one person out of the people commenting will be randomly selected and I will run a free 90 minutes session for her/his company (remotely, videoconferencing), doing this same exercise properly with Q&A session.

James Lyndsay and Bart Knaack from The Test Lab have used an instance of the app for testing purposes and people have found several defects. I am happy for that because I didn't do any exploratory testing or even took care of network failures or latency problems. Thanks for that guys!

This exercise will be part of my upcoming book on Agile JavaScript for Rich Internet Applications. I expect to have the book done in 2014.

If you want to have a look at the sample deployed app on Heroku, use these urls:
Load a page in the browser with this url (as a speaker).
Then load the page as the audience in other window.
Then just interact.

Thank you very much for all your support, I really appreciated you invested your time on my talk. If are there questions please let me know of find me tomorrow in the conference to catch up or hang out :-)

WebSockets and Android

I didn't know that the default browser installed on Android is called Webview. I haven't created any native Android app ever. But I wanted my web app to run on Android using Websockets. Unfortunately, websockets are not implemented in Android Webview.

In modern browsers, HTML5 provides a websocket API:

  1.  
  2. ws = new WebSocket('ws://' + host + ':'+ port);
  3. ws.onmessage = function(msg){
  4. var data = JSON.parse(msg.data);
  5. ws.send(JSON.stringify({message: 'OK cool!'}));
  6. };
  7.  

You don't need to include any JavaScript file in order for this to be valid code in modern browsers (when I saw it for the first time I was like.... "yeah cool but what library are you using?). Well you'd need a Websocket server. I've been trying ws for Node. It works very well with express.js and is very simple:

  1.  
  2. var WebSocketServer = require('ws').Server;
  3. var wss = new WebSocketServer({server: server}); // server is express' server instance.
  4. var clients = [];
  5.  
  6. wss.on('connection', function(ws) {
  7. console.log('connected');
  8. clients.push(ws);
  9. ws.on('close', function(){
  10. console.log('client closing');
  11. });
  12. ws.on('message', function(msg){
  13. console.log('message received');
  14. for (var i = 0, len = clients.length; i < len; i++)
  15. try {
  16. // do not use try-catch here, do it properly
  17. if (clients[i])
  18. clients[i].send(msg);
  19. }
  20. catch(e){
  21. clients[i] = null;
  22. }
  23. });
  24. });
  25.  

The code above is broadcasting a message to all connected clients.

It's very nice but it doesn't work on Android!

Workarounds:

  • Install Firefox or Chrome for Android, they support Websockets
  • Use a library that supports fall back to XHR long polling like Socket.io
  • Use Apache Cordova (phonegap) to create an Android app
  • Use a Flash implementation of websockets

If you use Apache Cordova you need to "provide" the websockets funcionality into webview using Java code. There are several plugins for that:

I haven't used any of those. The disadvantage is that users have to install an application. I just want them to use my web app without installing anything so I've discarded this option.

The flash implementation has some security constraints imposed by flash. I haven't dug into the subject much but I believe I need to open port 843 on the server and I can't do that on some PAAS providers. I can't confirm this, I might be wrong. The other thing is that browser needs the flash plugin. Take a look at this implementation (web-socket-js).

Eventually I've come back to Socket.io. Although people say it's outdated and it's got a poor websockets RFC implementation, it works very well for basic stuff and falls back to XHR long polling automatically:

  1.  
  2. var io = require('socket.io').listen(server); // server is express' server instance
  3. io.configure(function () {
  4. io.set("transports", ["websocket", "xhr-polling"]); // support both
  5. io.set("polling duration", 10);
  6. });
  7.  
  8. io.sockets.on('connection', function(socket){
  9. socket.on("sendMessage", function(msg){
  10. io.sockets.emit("messageReceived", msg); // broadcasting
  11. });
  12. });
  13.  
  14.  

On modern browsers implementing websockets, it will use them. On Android it will just use long polling.

To finish off, just remember that your mobile device and your desktop pc are two separate machines. If your client side js is trying to connect to "localhost" as the websockets server, it's not going to work from your mobile. I know it's absolutely obvious but I wasted more time than I expected not realizing that I had the wrong url in the client side js. It was written "localhost" rather than "192.168.0.100" for my tests using the Local Area Network. It was one of those silly mistakes that steal one's time more than they should :-(