Archive for the ‘JavaScript’ Category



Next week, I'll be taking part in the London Tester Gathering Workshops at SkillsMatter. I'll be giving a 4 hours workshop on JavaScript aimed at software testers on Thursday. Inspired by the workshop, I am working on a JavaScript manual for testers (JavaScript4Testers) that will be available soon. The manual will serve as a guide along the workshop and in the future it might become a book, because my friend Tony Bruce is now co-authoring it with me, which is very exciting. The manual contains already some brief sections on the JavaScript language and then it addresses testing techniques, debugging, tools and some tips on performance and security. If you think this manual is looking interesting, please go to its site and write down your name an email, that will encourage us even more.

Like all my workshops, it will be a hands-on session with very little theory and lots of practice. That is how I enjoy running workshops and the way people learn more.

I am a developer, am not a tester. In fact I am terrible at catching defects. But I love working together with testers because I like their vision and their collaboration spirit. Working together is very nice and effective. And I learn techniques on how to break the software by observing them. So I am looking forward to meeting all the participants in what is going to be a great experience. The workshop's atmosphere at SkillsMatter is very friendly, we'll have plenty of time to chat, share experiences, learn and enjoy. This is the Twitter hashtag for this edition: #ltgw2013

I land in London on Wednesday 16 afternoon. To warm up and meet  friends, a bunch of developers will meet in this pub to practice coding (a code kata) at 7pm. Feel free to join us.

See you next week in London 😀

A week in the UK

Talking at SkillsMatter

Last week was very intense indeed. I gave my first talk at Skills Matter (video here).

BDD for RIAs with JavaScript - Skills Matter from Carlos Ble

I must say I am not content with my talk because my English was rubbish but on the other hand I am glad that it provided value to some attendees. That is why I did it. I am also glad because it gave me the opportunity to meet very nice people (we were having some chats before the talk, and afterwards in the pub). And I will do better the next time 🙂 I have learned several lessons.

First one, I will not give talks right after landing a plane. The fact that I could arrive late if the flight or the train was late, made me very nervous, I went running to the venue and it doesn't help to concentrate. I must fly the day before.

Second one, when I talk in English, I must have pretty much everything I want to say written in cards so that if I can't find the words, I can just read. My English is not too bad when I am relaxed but under pressure, it's much harder to find the words and pronounce. When giving a talk, I pay close attention to attendees, timing and the way I am expressing myself. All these concerns difficult my capacity to talk in English.
I'll be talking advanced English lessons with natives, aiming to get fluent some day. But in the meanwhile I must have the written speech as a backup.
When my friend Ivan Stepaniuk and I gave a talk in the Agile Testing Days last year, everything was written and it went better. Also the fact that we were two guys made it easier.

Third one, audience's feedback is different depending on the culture. When I talk in Spain I can clearly read faces and see if they follow me or not. But this time it was really hard for me to now if they were following me. I must not loose concentration regardless of my difficulties interpreting audience's feedback, but just keep going unless they actively ask.

Fourth, talking with braces is f***g annoying! 🙂

If I keep practicing and taking lessons, with the help of a trainer I'll become better.

Participating in the SocratesUK open space

The following days I participated in the #socratesuk open space, organized by the London Software Craftsmanship Community.
2013-09-21 18.31.10

A great event in the countryside, an incredible venue.

It started with lightning talks and a fish bowl. The next two days there were talks, discussions and time for pairing with people. Pairing was the part I enjoyed the most. After dinner people used to meet in the bar to talk, drink and pair.
The last day we spent the morning hiking together along the countryside in a beautiful sunny day.

2013-09-19 16.23.52

Rachel Davies did an excellent job facilitating the whole event. And people were friendly and willing to share and learn

Having everything in the same place was very handy to meet different people. And the food was good. I've learned, shared, and met very nice people. It's been totally worth participating.

Thank you very much to the organizers and all the participants.
2013-09-22 10.26.53

I'd like to participate in Socrates Germany next year as well as Socrates UK.

Several people said we must organize Socrates Canarias. What do you think? shall we? 🙂

See more pictures here

 

 

 

 

Rich internet applications bring a powerful user experience. But in order to achieve that, they must be written totally different from traditional webs. The paradigm is totally different and so the architecture.  There is no "server side" as such. In some cases it's just a deployment site, where you have to browse in order to load the app. In some other cases you also need a centralized site to:

  • Initializing the application (deployment).
  • Storing data to be shared among instances/users (persistence).  
  • Connecting instances/users to each other (communication). 
Rather than calling it "server side", let's call it the hub. Its architecture must contemplate mainly:
  • Security
  • Concurrency
  • Scalability 
But everything else, lives in the application. The business domain, lives in the desktop application (which is inside the browser). There might be some security constraints related to the business that need to be tackled by the hub. In those cases, that particular bit of the business lives in the hub.

In order to be productive, the hub must understand JSON very well (assuming the data is sent/loaded via JSON) and serialize/deserialize it to objects automatically, without the need for hand-written mappings. This is one of the reasons why using Node.js in the backend makes sense, because you don't have to rewrite your objects in two different languages. Anyway, I am using C# and Python as the backend languages in two of my projects and the idea is the same.
If there are no particular security constraints, hub must accept data sent from the application and store it without objection.  The best way to avoid objections is using schemaless databases like Mongo.
Fortunately C# with ASP.Net is fantastic for JSON serialization/deserialization. For Python we've had to write code ourselves to get some automated conversion working.

As the hub is not the core, its functional requirements emerge from the incremental design. Such a design starts in the application side which eventually might need to send or retrieve some data to the hub. So my Cucumber scenarios, talk to JavaScript in the application side, specially if they are end to end.

Examples:
- Adding a "comment" to a "merchant" (where merchant is an entity, and comment is a value object): is done by the application. The hub just stores the entity as sent by the app. It  might have a security check to make sure the logged user can make changes in the merchant.  If there is any additional specific security constraint saying that comments can be made only by certain users, then we need to check that in the hub too, for the sake of data consistency. But that validation would go into the security rule's code. The hub's "merchant service/repository" won't know anything about comments.
- When listing merchants, show only those from  a particular country: is done in the hub. If the security constraint says that logged users from the UK can only work with merchants from the UK, we can't send all the merchants to the app for it to filter them out. Instead, the hub makes sure that only the information that can be seen in the app is sent.

So for rich internet applications, the hub is there just to support the architecture. Don't start the implementation of a feature in the hub, because you don't know if you are going to need it.  Keep your hub layer as thin as possible,  adding complexity only when proven necessary.
This will be probably a  chapter in my upcoming book where I will explain it in more detail.

The rationale behind:
The reason why desktop applications provide much better user experience than server-side web apps, is because they react immediately to user input. They interact in real time. When the user asks the application to save some data, the app should immediately tell the user data is saved, even if it hasn't got confirmation from the hub. If the hub doesn't respond or informs about a problem storing the data, then the application should inform the user, handling that somehow. But it should not make the user wait. So the application must have all the business knowledge to implement this solution.
Imagine a desktop application, a text editor for example. Now imagine it runs in the browser. All you need the hub for, is to load the application. If you want to access your text documents from different machines, then you need a hub to store and serve that information. Why do you need any business logic in the hub? What for?
In a later version, we decide to implement a new feature: collaboration with other users. There might be security restrictions. You might not want to have all the users opening your documents, but just some. Then you go and add a filter in the hub.
So it's not that you design some kind of service in the hub first and then call it from the application. It's the other way around, like in TDD, I might write a call to a centralized service that doesn't exist yet, once I know I need it in my application and once I know how I want it to behave. Then I add that behavior in the hub if necessary.
Eventually if the interaction among users is very complex, the hub will become complex and will contain important business logic, but its design will emerge according to the needs of the application and not the other way around.

This was SpainJS 2013

The 2nd edition of the SpainJS conference was held in Madrid last week. On Thursday there were workshops the whole day. Talks and networking happened on Friday and Saturday.

I attended to the workshops and learned a lot in the first one, about memory leaks hunting with Gonzalo Ruiz de Villa (@gruizdevilla). What I remember the most from Gonzalo's workshop is that timers (setTimeout and setInterval) are by far the most common source of memory leaks. The other thing is that Google Chrome has excellent built-in tools to watch for memory leaks. The memory consumed by the application should not grow as time passes, it should be stable. The online exercises prepared by Gonzalo are really good and very clear. It's worth studying them.

I missed the other workshops as I had to work a lot, but that is another story. All I can say is that people from the other workshops were very nice. I found the time to have a quick chat with them.  Now let's talk about the actual conference:

This year's venue wasn't as nice as last year's one, because last year it was in the middle of the park. Also the sound wasn't the best when speakers were on the stage. But everything else was very good in my opinion. In my experience this kind of small things happen when the conference is cheap. But I think they didn't have a negative impact on the conference. The organization was very good, the networking was excellent and the contents were brilliant. I will definitely attend next year if I can make it. I left the conference before the end as I was flying in the evening, so I missed the last 4 talks, which according to twitter were very appreciated by the audience.

These are the things I remember from the talks I liked the most:

  • From Douglas Crockford: the pragmatic approach when designing languages. The advises/hints in his slides were very good. And the reflection on the fact that developers choose languages because of fashion rather than professionalism. Smalltalk had more convenient design than C++ but still C++ got more popularity among developers. A very similar talk by Crockford can be seen online.
  • From Martin Naumann: proof things by yourself, don't just believe everything people say about tools and frameworks, and choose whatever that works better for you.
  • From Robert Nyman: first of all, his sense of humor. Very nice talk. The guys at Mozilla are working hard to facilitate Internet access to people in the third world. FirefoxOS can run in really  cheap devices and it's totally web based. Last week Telefonica started selling a new cheap phone with FirefoxOS. Looks like they (Mozilla) are working towards a better world. And I really love the idea. I'll see how can I contribute with the Mozilla Fundation.
  • From Tomas Perez & Jose M. Perez: localStorage has it's drawbacks and it's not a silver bullet. You've got to be defensive when accessing keys.  iFrames along with window.postMessage are sill good to communicate different applications, and sometimes, the only choice.
  • From Reg Braithwaite: programming languages can be used poorly or professionally. He demonstrated how a very complex problem can be solved with JavaScript in the browser, rather than with a big cluster of computers. Reg is author of the fabulous book JavaScript Allonge. My friend @pasku1 told me about this book some months ago and I am already using this style in my JavaScript. I am very happy with it. I am no longer using the "new" keyword in JavaScript and I have no more problems with the "this" keyword. I totally recommend the book.
  • From Peter Christensen: there are JavaScript APIs to talk to hardware devices like Arduino or Rasberry pi, like Johny Five. And there are people (makers) doing all kind of original and crazy projects all over the world.
  • From Axel Rauschmayer: if you don't want to have trouble with JavaScript, respect the Liskov Substitution Principle. Don't ask for types in your functions, to  do different things based on types. Also notice that on iframes, the rules change and it doesn't work the way you expect. The slides are a very good summary. They are here.

I met a lot of interesting people and also good friends. The lunch breaks and the night party were really good to meet people and talk. Friday's party was awesome, indeed. I planned to leave the party at 10pm, as I had a few things to do,  but I eventually left after midnight because of all the interesting conversations that were there.

Let's see if people who attended to the other sessions write some opinions about th em.

This post will be updated as I gather and remember more information about my experience.

Thanks again to Israel Alcazar, Enrique Amodeo, Lorena V. Perez, Sam Lown, Fernando Martinez,  and all their colleagues who organized SpainJS. Very well done guys, excellent conference.

Pictures here

 

 

 

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:

  1. 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.

  1.  
  2. function Message(sender, body){
  3. this.sender = sender;
  4. this.body = body;
  5. }
  6. var message = new Message();
  7.  

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:

  1.  
  2. function TicketSalesService(){
  3. var self = this;
  4. // ... some other code over here...
  5. this.buyTickets = function(quantity) {
  6. purchaseOrder.quantity = quantity;
  7. // THIS IS THE CODE WITH PROMISES:
  8. this.server.isUserRegistered(user)
  9. .then(tryToBuyTickets)
  10. .then(informSubscribersAboutPurchaseResult)
  11. .otherwise(function (err) {
  12. helpers.registerPromiseError(self, err);
  13. });
  14. };
  15. var tryToBuyTickets = function (response) {
  16. if (!response.registered){
  17. self.onRegistrationRequired(); // trigger event
  18. throw helpers.endOfPromiseChain; // stop the chain
  19. }
  20. return self.server.buyTickets(purchaseOrder);
  21. };
  22. var informSubscribersAboutPurchaseResult = function (response) {
  23. if (response.success)
  24. self.onPurchaseSuccess();
  25. else
  26. self.onPurchaseFailure(response.message);
  27. };
  28. this.onRegistrationRequired = function() {/* event */};
  29. this.onPurchaseSuccess = function() {/* event */};
  30. this.onPurchaseFailure = function() {/* event */};
  31. // ... some other code over here....
  32. };
  33.  

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

  1.  
  2. helpers.endOfPromiseChain; // this is just a constant, a string.
  3. // And this is a function to ease testing:
  4. helpers.registerPromiseError = function (target, err) {
  5. if (err != helpers.endOfPromiseChain){
  6. target.errorInPromise = err.toString();
  7. }
  8. };
  9.  

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.

  1.  
  2. Service.prototype.isUserRegistered = function (user) {
  3. var deferred = when.defer();
  4. // wrapping jQuery aja:
  5. this.requestData("theUrl/goes/over/here",
  6. { data: user },
  7. function(data) { // jQuery.ajax success invokes this
  8. deferred.resolve(data);
  9. });
  10. // TODO. call deferred.reject(); on error
  11. return deferred.promise;
  12. };
  13.  

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

  1.  
  2. it("triggers event when server responds that the user is not registered",
  3. function () {
  4. stubServerResponse(salesService.server, { registered: false });
  5. var promiseSpy = spyReturningPromise(salesService,
  6. "onRegistrationRequired");
  7.  
  8. salesService.buyTickets(5);
  9.  
  10. assertAsyncExpects(promiseSpy, salesService);
  11. });
  12.  
  13. it("tries to buy when server responds that the user is registered",
  14. function () {
  15. stubServerResponse(salesService.server, { registered: true });
  16. var promiseSpy = spyReturningPromise(salesService.server,
  17. "buyTickets");
  18.  
  19. salesService.buyTickets(5);
  20.  
  21. assertAsyncExpects(promiseSpy, salesService);
  22. });
  23.  
  24. it("triggers event when tickets are purchased",
  25. function () {
  26. stubServerResponse(salesService.server,
  27. {success: true, registered: true});
  28. var promiseSpy = spyReturningPromise(salesService,
  29. "onPurchaseSuccess");
  30.  
  31. salesService.buyTickets(5);
  32.  
  33. assertAsyncExpects(promiseSpy, salesService);
  34. });
  35.  
  36. it("triggers event when prescriptions could not be purchased",
  37. function () {
  38. stubServerResponse(salesService.server,
  39. {success: false, registered: true, message: 'fatal'});
  40. var promiseSpy = spyReturningPromise(salesService,
  41. "onPurchaseFailure");
  42.  
  43. salesService.buyTickets(5);
  44.  
  45. assertAsyncExpects(promiseSpy, salesService);
  46. });
  47.  

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:

  1.  
  2. var assertAsyncExpects =
  3. function(promiseSpy, target, additionalExpectation) {
  4. waitsFor(function () {
  5. return promiseSpy.called ||
  6. target.errorInPromise; }, 50
  7. );
  8. runs(function () {
  9. // this tells me if there was any unhandled exception:
  10. expect(target.errorInPromise).not.toBeDefined();
  11. // this asks the spy if everything was as expected:
  12. expect(promiseSpy.target[promiseSpy.methodName]
  13. ).toHaveBeenCalled();
  14. // optional expectations:
  15. if (additionalExpectation)
  16. additionalExpectation();
  17. });
  18. };
  19.  
  20. var spyReturningPromise =
  21. function(target, methodName) {
  22. var spyObj = {called: false,
  23. target: target,
  24. methodName: methodName};
  25. spyOn(target, methodName).andCallFake(function () {
  26. spyObj.called = true;
  27. return when.defer().promise;
  28. });
  29. return spyObj;
  30. }
  31.  

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

Event oriented programming promotes low coupling but not necessarily high cohesion. Always consider the Single Responsibility Principle while designing collaboration through events. I see three primary ways of collaboration:

One to One

A single object communicates with other (a collaborator). This can be done with dependency injection the same way we do it in Java or any other language (and you don't need Spring for that!). JavaScript provides another mechanism for one2one communication, the DOM Level 0 traditional way of event handling. A very useful and powerful way of adding hooks/ports to plug new behavior in, still promoting low coupling. If you need to change the collaboration in the future, from one2one towards one2many, it can be done easily. In some cases I see this as a more decoupled way of dependency injection.

  1.  
  2. function Car(){
  3. this.go = function(){
  4. /* some calculation over here */
  5. this.onLowFuel();
  6. };
  7. this.onLowFuel = function(){/* event */}
  8. }
  9. function RacingTeam(){
  10. function getReadyToFuel = function(){/* whatever */};
  11.  
  12. this.addCarToRace = function(car){
  13. car.onLowFuel = function(){
  14. console.log('low fuel!', this);
  15. getReadyToFuel();
  16. }
  17. };
  18. }
  19. var car = new Car();
  20. var team = new RacingTeam();
  21. team.addCarToRace(car);
  22.  

As you might realize I know nothing about car races 🙂 but I hope you understand the code. When implementing traditional dependency injection, the car knows it depends on a team, but it doesn't know the particular implementation of the team. With the DOM level-0 traditional way, the car doesn't even know it will be used in a team. All it knows is that it has to inform someone else about its fuel level when it gets low. However, the team's got to know about the car. Still the team should not know about the particular implementation of the car.
To test-drive this behavior, you probably need two steps. First one, make sure the car triggers the event and second, make sure the team handles the event. I wrote the two tests in a previous post. DOM level-0 traditional is the main mechanism I use for one to one collaboration, it's got however some pitfalls worth considering.

Pitfalls
  • You might not know some object is already handling the event: the handling mechanism is simple, we are just replacing the original function in the object triggering the event. If we try handle the same event twice, there will be only one handler, the last one. I always use the "on" prefix for those methods that trigger events as a convention to know it is an event with a single handler.
  • You might make mistakes with the "this" keyword: in the code above, what do you think "this" is when we invoke console.log? It's the car object, not the team. It's a problem with a very easy solution though. I usually have a reference to the handler doing "var self = this;". Some people prefer the "bind" method to do the same.

One to Many

For one to many collaboration there is the Observer pattern. jQuery implements the observer pattern to expose events such as "click":

  1.  
  2. $('#closeButton').click(function(){
  3. /* the event handler 1 */
  4. console.log('handler1');
  5. });
  6. $('#closeButton').click(function(){
  7. /* the event handler 2 */
  8. console.log('handler2);
  9. });
  10.  

When the button is clicked, both handlers are executed. When I implement the observer pattern in my objects, I prefer to make it explictly:

  1.  
  2. objectTriggeringTheEvents.addSubscriber('eventName', handler1);
  3. objectTriggeringTheEvents.addSubscriber('eventName', handler2);
  4.  

The "addSubscriber" makes clear to me, that I can have several subscribers. This is specially important to distinguish from one2one collaboration.
As an exercise I leave out to you the implementation of the observer pattern with TDD.
I use one2many collaboration when I really need the object to be observed by several objects, which happens to me, less often than one2one collaboration.

Many to Many

Different objects might trigger the same event and there might be a bunch of other objects subscribing that event. This is the case of a many2many collaboration. Or, I might not be interested in the source of the event, I might just want to handle it. This usually happens at the infrastructure level. For example I use it to know when the window is being closed. I don't care who is responsible for realizing the window is being closed but I do want to know it in several parts of my application to shutdown properly. So I create an object which subscribes to "window.onbeforeunload" to be aware of window closing and in turn, emits the event through a "bus" where subscribers are listening.
This is the less coupled way of interaction between objects, but it comes with counterparts: code gets harder to follow. This is the publish/subscribe pattern. My advise is to use this pattern only when strictly necessary and not as a the default mechanism for event oriented programming.
There are several open source libraries implementing this pattern. As an exercise, try to develop it from scratch, test-first. This is the code I ended up with while implementing my own pub/sub:

  1.  
  2. EventBus = function(){
  3. var subscribersInfo = [];
  4.  
  5. this.addSubscriber = function(callback){
  6. var eventNames = [].slice.call(arguments).slice(1);
  7. subscribersInfo.push({
  8. subscriber: callback, eventNames: eventNames});
  9. };
  10.  
  11. this.emit = function(eventName, eventArgs){
  12. for(var i = 0, len = subscribersInfo.length; i < len; i++){
  13. var info = subscribersInfo[i];
  14. for (var j = 0, lenj = info.eventNames.length; j < lenj; j++){
  15. if (info.eventNames[j] == eventName)
  16. info.subscriber(eventName, eventArgs);
  17. }
  18. };
  19. }
  20. };
  21.  

Last month I was in Madrid talking about best practices for JavaScript RIAs, in the monthly meetup organized by MadridJS. Here you have the slides:


The talk was in Spanish. I expect to give this talk in upcoming conferencies, in English 🙂

jQuery UI draggable is so cool! However, if the draggable element (or any of its children) contains a scroll bar, clicking on it will result in the mouse pointer stuck on the whole draggable element forever. To avoid that, use the "cancel" option:

  1.  
  2. $('#theDraggable').draggable({
  3. cancel: "input, textarea, .someClass"
  4. });
  5.  

 
And it will work perfectly 🙂

At the time of this writing, I am using jQueryUI 1.8 version.

  • Newer Entries →