Last friday I did a tiny presentation at work around Knockout components, Web Components and the future to the web. I titled it: Back To The Future… Of the Web – Knockout Components – cause all my talks need an undelying geeky topic. Anyhow, if you are interested in taking a quick look at knockout components, you can get the slides at SpeakerDeck and the code samples on GitHub.
If you follow my blog assiduously, you may have been wondering for a while… where the heck are you?! Well…Worry not! I will tell you. For the past few weeks I have been preparing with a bunch of friends for East Sweden Hack 2014 – yeah, that’s a hackathon – and thus the sudden disappearance and blog-gy silence. The hackathon took place last weekend, I took a week of resting, and now here I am, full of energy and burning to write some code, articles and kick some butt.
As a soft re-start, I thought it would be nice to write a short article about my experience this year at ESH 2014, that will hopefully inspire you, dear friend, to join the next hackathon you have the chance to be at. Imagine this prospect: two days of hacking whatever you desire, however you desire, with whichever language, tools, libraries, frameworks, whateeevaaaa that you want. Use at least one API of those offered to you by East Sweden county (I am going to go with county although I have no clue how you would translate it to English. Anyhow, it is Östergötland in Swedish)… so use at least one API of those offered to you, and build something that improves in some way the life of those living in East Sweden. Sounds good right? Wait, there’s more! Food and beverages for the whole weekend, a nice and comfy venue and a prize for the winners to go and visit the Mecca of all-things-tech: Silicon Valley. Cool eh? :) Change a couple of details here and there, and I bet you have a similar event happening near you. Why not give it a try?
From left to up to down-right to up: Erik Claesson (UX Panda), Kristofer Palmvik, Jenny Widén, Jaime González García (Kung-Fu Panda)
And this is what we built during the hackathon: Pendel Panda an awesome app to encourage commuters (and people) to take the bus by making it as easy and pain-free as possible, and by providing a willing assistant to be with them every step along the way in the form a… grumpy panda bear. XD Yeah and there was some crazy shit that we never got to implement that would have changed the life of a commuter as we know it… XD But anyhow, even though we did not get as far and high as we would have liked, it was a blast.
- Cool Stuff
- Coding the whole weekend! (note that we got time to sleep between Saturday and Sunday)
- Having a very diverse team with different skill and strengths
- Super fun to follow the event on the twitters
- Building something that works in such a short time
- The organization that did an awesome job! Thank you!!
- All the teams that built something from nothingness, from flimsy idea to working prototype
- Using a new framework that we hadn’t used before: Ionic FTW
- Less Cool Stuff
- No internets the first couple of hours
- Using a new framework that we hand’t used before. It can bring a lot of pain sometimes xD
Oh! I forgot! We did not win. Gå 2.0 won (Gå is walk in Swedish, or… go but only when you mean… actually… on foot, or almost because… planes also… gå) . The app is meant to encourage people to walk more through the use of game mechanics and by making it more social, like, “come walk with me”… or “look I am walking!”. You should have seen their video presentation… that was something… Wait! You can actually see their presentation down there (see the dropbox link):
If you want to know more about how the hackathon went, there’s a ton of information, photos, videos on the East Sweden Hack 2014 website (beware because it is in Swedish).
Have an awesome week!!! And, if you ever have the chance to go to a hackathon, don’t hesitate, just go!
The inspiration corner is the space where I share talks, speeches, videos, articles, posts, whatever that helps me keep my motivation, energy and passion fresh. I hope will serve you as well as it does me.
I like to see myself like a beam of positiveness, an inexhaustible source of energy and unbending willpower. Sometimes, however, I get tired… veeery tired. In those moments, I find it is great to recharge with inspiring tales and stories of others. Like this one, the story of… every single developer on how he/she got started in writing software at the Hello World Podcast!.
Not just another technical podcast. Shawn Wildermuth brings you his “Hello World” podcast where we learn about how your favorite developers tell their story of how they got started writing software!
I was a little bit reticent against the idea of adding yet another podcast to my podcast list (I have to guard and protect my time, you know? ^ _ ^), so I held myself off from starting listening until about the podcast hit the 30th episode. Not my brightest moment that one, not at all, because this podcast is great! Go and check it out whenever you are in need of some inspiration.
Good job Shawn Wildermuth! Keep more episodes coming! :)
P.S. Everytime I hear Wildermuth it reminds of Neuromancer… Does that also happen to you? xD
> followed by the result of evaluating an statement, and that’s how you will be able to differentiate them. I recommend the Chrome Dev Tools REPL (Console) because it will let you copy/paste even the first type – biggish – code examples on the REPL.
Encapsulation is the packing of data and functions into a single component.
1 2 3 4 5 6 7 8 9 10 11 12 13 14
This will look familiar to you since we also have object literals in C#:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
1 2 3 4 5 6
1 2 3 4 5 6 7 8 9 10 11 12 13
Notice how the constructor, not only initializes an object with a set of values like in C#, but it also determines which properties an object is going to have. Effectively it works both as a constructor and a class definition (if we were to draw a parallelism with C#).
To create a new instance of a
Barbarian we use the
new keyword just like in C#:
1 2 3 4 5 6 7 8
This new instance is of type
Barbarian and all its properties are publicly available:
1 2 3 4 5 6 7 8 9 10 11 12
Information hiding is the principle of segregation of the design decisions in a computer program that are most likely to change, thus protecting other parts of the program from extensive modification if the design decision is changed.
We have closures in C# so I will not delve a lot on them but for this teeny tiny example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Which makes the
hp variables effectively private: They are no longer accessible from the outside.
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8 9 10 11
arguments, which behaves sort of like an array, but it is not an array, which contains all arguments passed to the function, and which can be used in the fashion below to mimic method overloading:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
- Fun Fact: the
lengthproperty of any function returns the number of arguments it expects (its arity). Isn’t that unexpected? XD
You can add new properties to any object by using the
1 2 3 4 5 6 7 8 9 10
And remove properties by using the
1 2 3 4 5 6 7 8
In object-oriented programming (OOP), inheritance is when an object or class is based on another object or class, using the same implementation (inheriting from a class) or specifying implementation to maintain the same behavior (realizing an interface; inheriting behavior). It is a mechanism for code reuse and to allow independent extensions of the original software via public classes and interfaces.
prototype property that holds an object that will act as a prototype – will provide shared properties – for all objects created via that function and the
new keyword. The
prototype object has in its turn a
constructor property that points back to the constructor function:
1 2 3 4 5 6 7 8 9
In the simplest inheritance scenario, you can create an inheritance hierarchy by setting the
prototype property of a
constructor function. By doing that, all objects instantiated using that
constructor function will inherit properties and methods from the
1 2 3 4 5 6 7 8
In a more common scenario you may have several custom prototypes in your inheritance hierarchy:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
1 2 3 4 5 6 7 8 9
It is important to note that each property defined in the
constructor function will be part of every single object instance, whilst each property defined in the
prototype will be shared amongst all object instances. Again:
constructorproperties and methods are defined in each instance
prototypeproperties and methods are only defined in the prototype. This emulates
properties. Methods can still refer to a particular instance by using the
A common idiom to avoid needing to write the
Function.prototype.property each time you want to update the prototype is to assign the prototype to a new object:
1 2 3 4 5 6 7 8 9 10 11 12 13
In summary once more, because this was weird as hell the first time I saw it, to emulate a C# class you would need to create a
constructor function that will contain the specific properties of each particular instance and a
prototype that will provide a series of shared methods and static members that will be shared across of all instances of a given type.
The Prototype Chain
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
In the example above, we can appreciate how within the
conan object instance, the
ravage method is part of the
Barbarian.prototype and the
toString method is part of the
Differentiating Between Object Properties and Prototype Properties
In order to know whether a property is part of the object itself or part of the prototype you can use the
1 2 3 4 5 6 7 8 9 10
Object Augmentation in Prototypes
In the same way we used object augmentation to add new properties to an object, we can use the same concept to add new properties to a prototype and, hence, make those properties available to any object that has that prototype:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
And so, we can see how after adding the
ravage method to the prototype, instances of
Barbarian that had been created previously, suddenly and auto-ma-gi-ca-lly get a new method. :O
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Or in one of the prototypes in the prototype chain:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
1 2 3 4 5 6 7 8 9 10 11 12
If you are not familiar with the
call methods, you just need to know that they let you call a function and explicitly specify the object that
this will refer to within the scope of the function:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
In the previous example you can see how, even though we have defined the
sayHi method in the
conan object, by using
call we can borrow the method and use it on a different object
logen. For additional information, take a look at the awesome MDN docs on apply and call.
Building on what we have learned so far, we can emulate classical inheritance as we known it in C# by:
- Making use of prototypical inheritance to ensure that any instance of an object inherits methods from its prototypes
- Making sure that each constructor function calls its base type constructor function using
applyso that any instance of an object contains all properties defined in each and every constructor.
I’ll illustrate this through an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
1 2 3 4 5 6 7
*Polymorphism* allows a function to be written to take an object of a certain type T, but also work correctly if passed an object that belongs to a type S that is a subtype of T
But this is probably best illustrated through an example. Imagine a roguelike RPG, and a game scene with our mighty hero bravely venturing herself inside an eery dungeon, risking her life for adventure and profit, turning a corner into a host of ravenous ghouls…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
So, as long as an object has the
draw method, it will behave as something that can be drawn regardless of inheritance. And thus the popular saying that you may have heard in the past…
If it walks like a duck, swims like a duck and quacks like a duck, I call it a duck.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
It looks awesome, doesn’t it? (Even though it is just syntactic sugar over all the concepts you have seen in this article).
For more information regarding ECMAScript 6 Harmony take a look at @lukehoban great summary at GitHub
Appendix B. A Note About
To us C# developers used to the reliable value of
The `this` parameter refers to an object that’s implicitly associated with the function invocation as is termed the *function context*. (…)
(…)as it turns out, what this parameter points to isn’t, as in Java, defined by how the function is declared, but by how it is *invoked*.
- If a function is invoked as a method in the context of an object (e.g.
thiswill point to the object itself. (Like in C#)
- If a function is invoked as a function (e.g. helloWorld())
thiswill be set to
window. If you are using strict mode (
undefinedsaving you from unexpected errors.
- If a function is invoked as a constructor with the new keyword then
thiswill be a new object.
- If a function is invoked with
applywe can set the
thisto point at whatever our heart desires
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
For more detailed information about the uses of
bind method to create functions that are for ever bound to a specific object.
Fare thee well friend! ^ _ ^
Other Awesome Resources
P.S.1. I had envisioned writing something more about higher level constructs to organize your code, and common design patterns, drawing parallels to the .NET world but I fear this article would have become undesirably long. I hope you will share my opinion and won’t be to hard on me if I leave it for a future article.
I have been following Mark Seemann for a while ‘cause this guy is as smart as it gets. He wrote a book on dependency injection, released two awesome courses on unit testing in Pluralsight, and has written the AutoFixture unit testing library (with many other contributors).
AutoFixture is a .NET library that helps you write unit tests with less code by providing:
- Test data generators for primitive and complex types (in a constrained non-deterministic way – the data generation algorithm can be customized)
- Test data builders for any type
- AutoMocking of dependencies
- I repeat, A U T O M O C K I N G of dependencies
and in words of Mark Seemann:
AutoFixture is an open source framework for .NET designed to minimize the ‘Arrange’ phase of your unit tests. Its primary goal is to allow developers to focus on what is being tested rather than how to setup the test scenario, by making it easier to create object graphs containing test data.
What does this means in terms of that application you are developing right now if you were to adopt AutoFixture just this very moment?
- Write less unit test code
- Bye writing mother objects
- Bye writing your own test data builders
- Bye to manually providing dependencies for your system under test
- But wait Joe! There’s more!
- By using a SUT (system under test) factory we effectively isolate all tests from changes in the SUT constructor. You will probably have handled this via factory methods, builders or fixture objects. But with AutoFixture and automocking, adding a new dependency to a constructor will not break any test!
- Being able to automock dependencies means that you don’t need to explicitly mock/stub dependencies that are not used in a given test, which in turns means that tests become more readable, intentional and deliberate. The code that it is there takes active part in the test. All crud is removed, gone, caput.
You can easily start using AutoFixture in your project via Nuaet:
1 2 3
Note: I am using Nunit and RhinoMocks in this article but there is support for many other testing frameworks and mocking libraries.
Where each of these packages consist in the following:
- AutoFixture: this is AutoFixture itself
- AutoFixture.NUnit2: this is an improved integration between AutoFixture and NUnit that allows AutoFixture to inject test data and SUT directly in NUnit Test methods
- AutoFixture.AutoRhinoMock: this allows auto mocking of dependencies via Rhino.Mocks
I am going to go fast like lightning through some of the interesting features provided by AutoFixture, brace yourself:
Auto Mocking SUT Dependencies
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
Test Builders For Any Type
1 2 3 4 5 6
Generating Test Data
1 2 3 4
Note For The Intrepid: AutoFixture doesn’t work well if there are cycles in the object graph. If a complex type has cycles, you will need to tell AutoFixture to leave that property alone (
OmitAutoProperties) or set it explicitely.
Integration with NUnit
If we do a full integration with NUnit we can remove the Arrange stage and inject the test data directly as arguments:
1 2 3 4 5 6 7 8
And even auto mock SUT dependencies:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Mind Officially Blown Away. Booom… Boooom…. Booom… Boooom…. Booooom….
It even has testimonials. Open-source library with testimonials?!? Whatz?!?:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
It is time to Experiment Thyselve! Go
NuGet Install-Package AutoFixture Now!
With Barbaric Book Reviews I bring you interesting reviews and useful insights from awesome books that I have read. I also bring myself the magic of everlasting memory so that I don’t forget these tidbits of knowledge as I grow old and wither.
I should read more UX books. We! [Developers] should read more UX books. They are filled with wondrous jewels of information about the arcane arts of psychology and human behavior, of inestimable value when crafting effective and engaging user experiences. They are also beautiful, I haven’t seen a UX/Design book that wasn’t in itself a wonderful and inviting artpiece of a book. (ehrr… Jaime, always sooo enthusiastic)
We recently started a book club and a library at work. In the book club we read a book a month and afterwards we discuss it (cool), in the library we have shared our books with each other for the betterment of the Universe and for great justice. That’s how I got to borrow this great book titled Seductive Interaction Design: Creating Playful, Fun and Effective User Experiences by @stephenanderson from my good friend (and UX whiz) Erik Claesson and Voilà! The article!
Seductive Interaction Design explores what lies beyond usability and takes us to the realm of emotions, that is, how can we design applications and services that are not only easy to use or convenient but pleasurable and meaningful. How can we design applications that can elicit an emotional connection in our users. How can we design applications that entice or seduce our users from the very first sight and into a long lasting relationship.
The setting is the Odenplan Metro Station in Stockholm, but we could easily be in the subway in New York or the Tube in London. There’s an escalator running next to a set of stairs, both leading up into the daylight. Only today something is different. An experiment is taking place. The stairs seemingly have been transformed into piano keys. Not only do they resemble the familiar black-and-white keys of a piano, but through the magic of technology - sensors attached to speakers - every step triggers the resonant sound of a piano key.
We watch as two people start to take the escalator, pause, then place a foot on the first step. A low, loud note rings through the station. They each take a few more steps, caution transforming into more of a leap in their step. The air is filled with the sound of a musical scale. We see more people approach, just curious at first, but soon the are **delighted**. For some people the goal is no longer to even exit the station - they step back and forth across the keys to create a melody.
What is going on here?
This is an experiment in behavior change: “Can we get more people to choose the stairs by making it fun to do?”
In summary, the book describes how to create applications that delight our users – like the piano staircase delighted all passers-by – and that lead them to behaviors of our own design – to make the healthy choice and choose the stairs instead of the mechanic ones. It does so, in a very clever way, by drawing a parallel story to the art of human seduction in four parts:
1) Aesthetics, Beauty and Behavior describes the importance of aesthetics and beauty, and enumerates a series of attributes that human beings find attractive. If it works with humans and is ingrained in our nature, why not harness that knowledge when building attractive applications? It might just work…
I found particularly interesting the idea that “contrary to popular opinion, things that are enjoyable will be perceived as easy to use and efficient”, that is, instead of thinking, an easy to use and efficient application is enjoyable, you invert the cause and the effect. It does make sense if you think of it. (That’s one of the things I love about reading, it estimulates active and intentional thinking and reflecting, reading FTW!)
2) Playful Seduction continues the trip into seduction-land through the idea of playfulness. In life, we use playful behaviors to entice others, behaviors such as humor, surprise or being misterious, all of these can be translated to the interactions we have with our users in our applications so they become more vibrant, more alive. And here goes an example from Southwest airlines where they use humor to provide that little extra bit that makes the experience more memorable:
In the event of a sudden loss of cabin pressure, oxygen masks will descend from the ceiling. Stop screaming, grab the mask, and pull it over your face. If you have a small child traveling with you, secure your mask before assisting with theirs. If you are traveling with two small children, decide now which one you love more.
Ladies and gentlemen, if you wish to smoke, the smoking section on this airplane is on the wing and if you can light’em, you can smoke’em.
There may be 50 ways to leave your lover, but there are only four ways out of this aircraft.
Hilarious. Can you see how leveraging playfulness can improve the connection between your users and the applications you develop?
3) The Subtle Art of Seduction guides us towards using subtlety, being suggestive, nudging our users in almost unperceptible ways to the desired behavior. An example of this can be found in Get Satisfaction:
(…) At one point you may have asked: “How can we get people to complete the requested information or add more written information in a text field?” The customer feedback app Get Satisfaction has an elegant way to nudge people into providing more information. With Get Satisfaction, you can share ideas, questions, problems or praise for a site or service your’re using.
Here’s the neat part: They estimate the likelihood of your post getting noticed based on how many fields you complete and how much text you type in each field. This strength meter is a real-time feedback loop.
(…) If I include more information, like additional details and some tags, then the strength meter goes up. If I add my feelings about it, the strength meter climbs higher still. So, it’s giving me that feedback and letting me know “Hey, we think you should add more information here”.
4) The Game of Seduction explores how to use game mechanics to keep our users hooked to our application in the long term. Within its pages, Steven details how to distill/reveal the challenges (the fun part) from your application and leverage these together with conflicts, choices, feedback loops, goals and rewards in order to create compelling and fun applications. And he does so by applying these game mechanics to the design of an email client, which makes for an excellent example that you can yourself use when applying this principle in your work. This is probably my favorite part of the book in addition to all the psychology principles.
3 Things I Have Learned From This Book
There’s a host of things I learned from this book, and even more ideas that I have found earlier in other literature which have been either reinforced or tackled from other interesting angles. Here are the three that were the most memorable to me (I usually take notes on the books themselves while a read them, but this one being borrowed I had to refrain myself and thus, these 3 points may not be the very best or the most interesting ones):
Awesome Thingy #1. The Status Quo Bias
Given a choice between action or inaction, we choose inaction, we do nothing. Given two choices, we tend to choose the one that doesn’t require us to do anything. This is what is known as the status quo bias. If you think about it for a minute you will recognize this behavior in yourself, think about every time you sign up for a free month subscription and then neglect to cancel it, or how you always choose to run in the same treadmill at the gym, or use the same locker in the changing rooms, that my friend is status quo bias in action.
Knowing the existence of this bias can help you leverage it to help your users when developing applications and in real life. Think about the use of good defaults or suggestions that nudge your users in the right direction. Think about understanding when the bias – the lizard brain – kicks in and saying: “No! I am going to break the status quo, get outside of my comfort zone and kick butt”.
The status quo bias is very related to other two interesting ideas in behavioral economics, the ownership bias (also known as the endownment effect) – we assign more value to things that we ourselves own– and loss aversion – we hate to lose stuff.
Interesting stuff right? Can you think about ways in which you could leverage this?
Awesome thingy #2. Bridging The Gap Between UX and Business. Connecting Behavior Goals With Business Goals
From my experience in software development so far, there’s usually a big gap between fulfilling business goals and User Experience. Oftentimes businesses struggle to understand the importance of User Experience and struggle even more when trying to incorporate User Experience into their software development process.
Seductive Interaction Design provides an interesting take on this by providing the following heuristic:
- Identify Business Goal: “What does successful look like?”
- for instance Improve the quality of the video content uploaded to YouTube
- Identify which behaviors support this goal
- Encourage people to be more selective about what they upload
- Design your application to encourage this behaviors and attain the business goal
- Limit the number of uploads to just a few per week. This will encourage people to upload only their best content
- Give more editing features to people that uploads HD content
- Start challenging users to include cinematic techniques in the videos. This would, in time, improve YouTube users video production abilities and thus the content they upload to the site.
This was super interesting to me because I have never thought about developing applications in these terms. I usually think in a smaller scale, designing to help the user fulfill a particular need but at a much smaller scale, like what is the user trying to achieve in this particular view? and How can I make it as easy and pleasurable as possible?.
I will definitely remember this in the future.
Awesome thingy #3. Mind Your Product Personality
Every product has a personality and we people are deeply affected by that:
- We identify and avoid certain personalities
- We trust based on personality
- Perception and expectations are linked to personality
- We choose products that are an extension of ourselves
- We treat advanced technology as though it were human
Mental note: Mind your product personality, does it appeal to your target audience? Is it consistent?
In Closing. Wholeheartedly Recommend This Book
And that was it. I don’t have the slightest idea how this article exploded as it did. If you’ve come this far, I really hope you have enjoyed it and that it has piqued your curiosity regarding the book.
Other Interesting Related Reads
Throughout the book, the author offers numerous references to other interesting books and sources. Below are those that I found the most interesting:
Dev Talk Monday is the series that brings you awesome dev talks every Monday
This weekend I had the chance to see a superb talk by Steven Sanderson on building large scale SPAs (Single Page Application) with Knockout.js. This talk is invaluable if you are spending any amount of time working with Knockout.js and are looking for tips on how to bring your front-end to 2014. You will learn:
- How to architect large applications with the new knockout.js components
- How to use yeoman, bower and grunt/gulp to boost your front-end development environment
- How to setup your testing environment with jasmine and karma
Also pretty awesome the fact that you can see all ndc 2014 talks on vimeo (and all ndc talks from all time back to the prehistoric age)
Ladies and gentlemen: The blog post you are about to read is based on a true story/e-mail. Only the names of classes and methods have been changed to protect the privacy and innocence of the source code. The facts remain unchanged and the contents unadultered…
Disclaimer: I love automated testing and I have been a practicioner of TDD since 2010.
When I refer to unit tests in this article I use the most strict definition of unit tests, that is, test a unit of code – a public method of a class – in complete isolation – by stubbing or mocking all its dependencies. When I refer to integration tests I mean testing classes that collaborate together. When I refer to acceptance tests I mean end-to-end tests.
Last Friday I sent a code review (what a wonderful invention the code review) to a friend and colleague, let’s call him D… hmm… Dumbledore! Yes! That will do. I sent a code review to Dumbledore and continued coding away. After a brief period of time Dumbledore dilligently went through my code and sent me the review back. I impatiently opened it and read:
It looks like you are testing an implementation detail.
Which started a great conversation about programming in general (what a wonderful invention the code review) and about testing behavior vs testing implementation in particular. I kept thinking about the testing behavior not implementation conundrum after work which lead me to write an email the day after and this blog post today. I think that some times I need time to think before I can articulate a good answer to stuff. Particularly with some techniques and practices that I have been doing for a while and I have internalized so much that I almost don’t question any more.
Here is what I concluded after some thought. The email read like this (foreground slowly fades into the past, the screen now in fuzzy shades of gray, Gmail):
I think that indeed the most ideal objective when testing is to test behavior, that’s what you really want to focus on when writing automated tests because it is the only real/final type of test that is going to tell you whether or not your application behaves in the way you want. But that means that, to really test behavior in complex systems you are going to need to write acceptance/integration tests (black-box tests), that is, expensive tests (expensive to setup and expensive to run). For instance, in the particular case that we were talking about in the code review, in order to write a real test of behavior I would have needed to write a black box test that would have tested the service, the inbox manager, any other inbox manager collaborators and probably a repository, NHibernate and the database. This is a huge investment and that’s why I usually like to write unit tests (test unit of code in isolation) instead when I am developing, particularly if I feel that time is running out XD (although in the best case scenario I would write an acceptance test and then TDD my way into a working implementation).
It is quite difficult to test behavior when writing a unit test for a complex class that has many collaborators, that in turn have more collaborators, that have in turn yet more collaborators. For instance,
- If you have a calculator with an add method that takes a couple of integers, then no problem, you can easily test behavior.
- If you have a console app that takes string arguments and adds them (string calculator kata?), you may have a class that does the arithmetic operations and an argument parser. You can test both individually for behavior and the whole console app with black box testing. Still no problem.
- If you have a huge application with tons of classes that depend on each other then testing gets harder. Black box testing becomes hard to setup and slow to run, so you lose one of the most useful/important characteristics of automated testing: short feedback loops. Something that quickly tells you that your code is [not] working as expected, and does it fast.
In case number 3, the case we find ourselves at. You have classes with tons of nested collaborators. You can, and should write acceptance tests, but the feedback loop for these tests is soooooooo slow. You write them, build, start backend, “ups, I made a stupid error”, fix, build, start backend, dammit, another error, and so on and so forth… that’s why, testing with acceptace tests is painful, and that’s where the value of unit tests lie. I can write a test, red, write code, green, refactor, green, write test, red, write code, green, refactor, green and so on super fast so that when I am ready to run the acceptance test I am in a position where I am pretty sure that it will pass.
And this brings us to the problem, How can I write unit tests for complex systems so I can test behavior instead of an implementation?. And that is a tricky question that requires consideration. In the case we are discussing about, I very distinctly tested an implementation:
ShouldGetTheFoldersViaTheInboxManager_WhenCalled (or something like that) where I asserted that a collaborator’s method had been called.
I could make it more behavior-y (and that’s an improvement indeed) by changing its name and body:
ShouldGetTheFoldersIntheUsersInbox_WhenCalled where I would setup the inbox manager stub and test that the service returns the aforementioned folders.
This is an improvement indeed but it still has a problem. I am testing an implementation disguised as a behavior. Why? Because I have explicitly set up the stub. (This test is the equivalent to the mock assertion, I just changed the side of the coin, particularly in this case where the only thing the method does is delegate)
In order to really test behavior in this particular case I think we would need to do a couple of things:
- Answer the question: What part of my code is just an implementation? How many collaborators and how deep are just part of this implementation detail? That would probably end up in us dividing the application in additional submodules with a more strict separation (which would be a good thing). We usually achieve this through projects/assemblies/layers, but it would be probably interesting to make use of more private classes and start thinking more deeply about when we use DI (dependency inversion) and IoC (inversion of control) to make an explicit separation between implementation details and the contract/service a given module fulfills/provides.
- Since we are using IoC heavily, we would need to improve our testing development environment to be able to inject all the dependencies that are part of the implementation, so that you won’t need to do that manually, and thus save time and pain.
Another different question is, is there value in unit tests that test an implementation? or is there value in testing units of code in isolation (because I think that most cases they are the same thing)?
The pros that I see in writing unit tests are the ones that I have always seen:
- test ensures the code behaves as I want it to behave
- fast to write, fast to run, short feedback loop, good value for price
- find bugs with super-high granularity (if a unit test shows a bug, you pretty much know which class it is in, you don’t need to go throw all classes nor debug it, that’s priceless)
- it forces you to write very simple classes and increase modularity and separation of concerns (because writing unit tests for fat, complex classes with tons of collaborators is horrible. We have a natural tendency to avoid pain)
- increases developer confidence to refactor
- documentation for my future self and other developers
- if something changes that affects the unit under test, you will know it (regardless if it is a bug or a new implementation xD)
The cons are the ones that I have learnt to live with and that have made me reflect on improving the way I test:
- they can be brittle in the sense that changes in the implementation may break your tests
- they are not as trustworthy as higher level tests. You can make assumptions when stubbing collaborators that do not match reality and end up testing… something different
For instance, in the case of the calculator console app, you could have a calculator class that would call an argument parser to parse the arguments and then call the arithmetic unit to perform the arithmetics on those parameters. You could write a test to test that the calculator behaves in that way.
GivenTwoNumbers_ShouldReturnItsSum and you would setup two stubs to do the parsing and the arithmetic calculation. The calculator class itself doesn’t do much, it justs delegates argument parsing to an argument parser class and arithmetic calculations to the other class. If you write a test to verify that the calculator behaves in that way, you are pretty much testing that algorithm: 1) parse 2)arithmetics, but more explicitely, there’s some
IArgumentParser that is going to parse the arguments and some
IArithmeticsUnit that is going to add them. What do you gain by writing this test? this particular test is of marginal value if you compare it to the unit tests for the arithmetic and the parser classes but you still gain something: 1) you know that the class works in the way you want, without the test, how would you know it works at all? 2) If you run the app and there’s a bug, you are going to be pretty sure that the bug is not in the calculator but in other dependencies.
And that’s pretty much it… I have to think about other specific examples within our application MagicFlow …
hmm… this could be a blog post xDDD
(foreground distorts into reality, welcome back to the present) And that was the email. Hope you found it interesting and feel free to comment and share your thoughs about unit testing and TDD!
I have been thinking for a while about writing more articles regarding my experience and journey with unit testing and TDD, so expect more of them coming. And particularly at this point where I am starting to question the definition of unit tests in isolation I learnt from the art of unit testing. All hope is not lost, I was just a liiiiitle bit slower than Roy :)
I used to feel that a ‘unit’ was the smallest possible part of a code base (a method, really). But in the past couple of years I’ve changed my mind. Here’s how I define a unit test, as of October 2011:
A unit test is an automated piece of code that invokes a unit of work in the system and then checks a single assumption about the behavior of that unit of work.
A unit of work is a single logical functional use case in the system that can be invoked by some public interface (in most cases). A unit of work can span a single method, a whole class or multiple classes working together to achieve one single logical purpose that can be verified.
Some Interesting references
Oh yesss… I just dit it… I just wrote a 5 things X blogpost… God save my soul.
Ok, now that I’ve got your attention (this 5 things X blog post titles never fail in that) I will continue writing a little bit more about how my experience with codealike has been so far. This article was actually meant to be part of the Boost Your Productivity With Codealike Insights review but, for once, I had the good judgement to show it to my girlfriend Malin first who wisely advised me to split it appart “I got bored after the 8th paragraph Jaime” – She said, and She was right… as usual (you may be nodding at this point XD).
1. Once and for All I have Irrefutable Proof That I Love Coding
Yes, you read it right. Once and for all I have irrefutable, specific, real proof that I love coding. Check this out. This right here is my productivity pattern per machine.
From it we can reach to several conclusions:
- You now know my machine’s name, I may have to kill you
- I wake up at 5 a.m. and code
- Looks like sometimes I stay and work too late :(
- Either my productivity sucks the whole day OR I am unusually uber-productive between 6 and 7 because I want to go home… so that I can… cuddle with Malin (…and code apparently)
2. Each Debug Session is a Failure
As a deep believer and practitioner of TDD and a member of the league of extraordinary gentle-unit-testers debugging is a failure. Every time I have to click that F5 and go into debug mode is a reminder of that moment of weakness when I decided not write a unit test, or that time I let a teeny tiny corner of the source code rot just enough… This month I failed 26 times. But next month will be better, one test/refactoring at a time, hell yeah.
3. You Can Drill Down to the Minutest Detail
Oh, by the by, in C# code you can drill down to methods and not only see files.
4. You Can Healthily Compete With Your Teammates
Here you can see how this week is going so far. Daniel is kicking my butt, I have coded almost nil this week. That doesn’t necessarily mean I haven’t contributed to the team… I am funny:
And wait… yes, picture this. In a not too distant future codealike could add a gaming layer. You and your teammates would be able play games with each other based on the data in codealike, like… who’s the first to code 40 hours this month or…
5. My Coderbits Profile Is Getting Beefed Up
6. You can Get a Nice Summary Of The Languages You Use The Most
Look at this nice profile called Your Facts:
Ok, and that was it for the awesome stuff. Enough of the good cop. Time for some harshness and criticism.
-1. How the Heck Do I Change my Profile Picture?
No… for real… how do I change my profile picture?
-2. I Need More Education
Once thing that you will start feeling after using codealike for a short while is confusion (and curiosity XD). Particularly, you will ask yourself, where do these numbers come from? Why does it look like that I am working so few? Does the plugin fail to connect to the backend and some data is missed? Do I really work so few? But it cannot be…
So it would be pretty great if the guys at codealike could devise a way to educate us, their users, to better understand the data. And additionally, if they could, of course still leave the capability of being able to drill into the data, but dumb it down and provide more aggregation, tailored advice and more specific easy-to-understand KPIs. That would be great.
Well, that’s all for now. I was a little bit all over the place but I hope you liked it (and secretly wish that you had a laugh or two) :). Have a good one.
P.S. I just found out that there’s a Windows Phone Codealike app! Check that out…
The Barbaric Development Toolbox is a series of posts where I write about awesome and indispensable tools and libraries that enhance productivity and make our lives as software developers much easier and enjoyable.
I have seen very few people as crazy about productivity as we software developers. I have no idea where that tendency or behavior comes from, but the truth is that we spend countless hours learning every shortcut there is to improve our programming fu. We learn to master our IDEs and text editors, put up with the steep learning curve of vim, or the strange incantations of Emacs. We use tools like ReSharper, JustCode or CodeRush, and learn disciplines like GTD or the Pomodoro Technique. All and everything just to be able to do more, to be better, to master our craft.
What if I told you that there is a new super interesting, innovative and all-hands-down-just-cool tool that lets you monitor every second of every minute you spend in Visual Studio? What if I told you that you can see how much time you spend reading, coding, building and debugging? How much time you do either of these things within a solution, a project, a class and to the minutest detail: a method!? Or which hours of the day you are more productive at, or which languages you use most often? What would you do with this kind of information?!? Behold!! Because codealike is here and is bringing all these insights and more to your nearest Visual Studio!
codealike is a Visual Studio (and Eclipse) plugin that records enormous amounts of information on how you spend your time in Visual Studio, and then weaves it in wonderful and insightful ways so that you can take the most value out of it. With codealike you can look at your code and your work patterns in a total different way than ever before. You can divine the secret story of your code, because your code has a story to tell and, until now, you haven’t been listening.
But let’s be less fluffy and go down to the specifics. These are some cool things you can find out with codealike:
- How much time you have spent coding, debugging, building and outside of Visual Studio
- How often you were interrupted in a given period of time
- How many times you’ve been on fire (in the mythical flow)
- How focused you were during a period of time and in different machines
- See in which solutions, projects, files, classes and methods you spend the most time
- See which programming languages, frameworks you spend time using
- See a very detailed timeline of how and where you spent your day
- Analyze the nitty-gritty details on how you spend your time in every solution, project, file, class and method
- Rank and compare yourself to other codealike users
- Compare yourself with a version of you from another space and time (to see how you have improved as the time passes)
- Use it within your team and get a holistic view on how the whole team is doing.
Which is infinitely better put forward in this video:
If you want to start learning more about how you code, go to codealike.com and create a free account. You just need to sign-up, download the plugin and get rolling.
VIP Premium Licenses Limited Time Offer
I have a limited time offer brought to you directly by the codealike guys. I have 30 premium licenses for a whole year to give away to you and an unlimited number of 20% discounts. The only thing you need to do is to tweet and share this blog post and reach me on twitter or via mail for your reward. It would be beyond awesome if you could write a comment about what you think about codealike, your favorite feature, is there anything that you are missing? or whatever crosses your mind at that particular moment in time.
The licenses and discounts are only available until the 2nd of August. Be swift.
I have been using RescueTime for a while (ever since I heard about it in Scott Halseman’s great talk on productivity), and when codealike came out I went bananas. What!? This is RescueTime for .NET developers!! A w e s o me! There’s no need to say that I started using it right away.
It was a great idea, but I was a little bit disappointed with the information it initially provided as it felt quite scarce and of little utility – I think that is how I remember it although my mind may be playing tricks on me. Anyhow, what I want to get to, is to the surprise I felt when, a month after I started using it, codealike had become ten times better. And so it has continued, getting better and better at an amazing speed.
Today codealike provides a lot of interesting and helpful information, but I cannot help to think about all the possibilities and usages of all that information that are yet to come, all the tailored advice based on your personal data. The sky is the limit guys. :) (nope, I couldn’t resist the smiley).
Appendix, or on Another Interesting Less Known Facts About Codealike and its Makers
Did you know that…
- codealike uses RavenDB on Azure and released the first version of codealike in 6 weeks?
- the codealike guys collected some interesting insights on how we developers code based on the information they collected last year on 2013?
- corvalius, the company behind codealike, is an Argentinian company with an awesome manifesto we should all learn from?