Wednesday, December 30, 2015

Books I read (2015)

January
- Software Architecture for Developers, Simon Brown
- Functional Programming Patterns in Scala and Clojure, Michael Bevilacqua-Linn
- Working Effectively with Unit Tests, Jay Fields

February
- Vida y Destino (Жизнь и судьба), Vasili Grossman. (2nd time)
- Primer Libro de Lankhmar (The First Book of Lankhmar), Fritz Leiber
- Drown, Junot Díaz
- Los girasoles ciegos, Alberto Méndez
- Smalltalk Best Practice Patterns, Kent Beck

March
- Las puertas del paraiso (The Vagrants), Yiyun Li
- Growing Object-Oriented Software Guided by Tests, Steve Freeman and Nat Pryce. (2nd time)
- The Joy of Clojure, 2nd edition, Michael Fogus and Chris Houser

April
- Las ciudades carnales (Les cités charnelles), Zoé Oldenbourg
- Refactoring: Improving the Design of Existing Code, Fowler, Beck, Brant, Opdyke and Roberts. (2nd time)
- Hasta aquí hemos llegado (Τίτλοι τέλους), Petros Márkaris
- The Childhood of Jesus, J. M. Coetzee

May
- Refactoring to Patterns, Joshua Kerievsky
- You Don't Know JS: Scope & Closures, Kyle Simpson
- Ser, Ignacio Terzano
- Slow Man, J. M. Coetzee
- Número Cero (Numero Zero), Umberto Eco
- La vieja sirena, José Luis Sampedro
- The Death of Bunny Munro, Nick Cave

June
- Martha and Hanwell, Zadie Smith
- You Don't Know JS: this & Object Prototypes, Kyle Simpson
- Functional Programming for the Object-Oriented Programmer, Brian Marick

July
- Object Thinking, David West
- The RSpec Book: Behaviour Driven Development with RSpec, Cucumber, and Friends. Chelimsky, Astels, Helmkamp, North, Dennis and Hellesoy
- The Nature of Software Development: Keep It Simple, Make It Valuable, Build It Piece by Piece, Ron Jeffries
- Domain-Driven Design: Tackling Complexity in the Heart of Software, Eric Evans
- Momo, Michael Ende

August
- Los Surcos del Azar, Paco Roca
- En el pueblo del gato vampiro (Village of the Vampire Cat), Lensey Namioka (2nd time)
- El valle de los cerezos rotos (Valley of the Broken Cherry Trees), Lensey Namioka (2nd time)
- Design Patterns in Ruby, Russ Olsen
- Practical Object-Oriented Design in Ruby, Sandi Metz (2nd time)
- En el café de la juventud perdida (Dans le café de la jeunesse perdue), Patrick Modiano

September
- Your Code as a Crime Scene: Use Forensic Techniques to Arrest Defects, Bottlenecks, and Bad Design in Your Programs, Adam Tornhill
- Cien años de soledad, Gabriel García Márquez
- Eloquent Ruby, Russ Olsen (2nd time)

October
- Understanding Computation. From Simple Machines to Impossible Programs, Tom Stuart
- A Mind For Numbers: How to Excel at Math and Science, Barbara Oakley

November
- The Well-Grounded Rubyist, 2nd edition, David A. Black
- Hackers & Painters: Big Ideas from the Computer Age, Paul Graham
- Effective Programming: More than Writing Code, Jeff Atwood

December
- The Psychology of Computer Programming: Silver Anniversary, Gerald Weinberg
- Cuando el árbol canta (When the tree sings), Stratis Haviaras
- Nineteen Eighty-Four, George Orwell
- Thinking, Fast and Slow, Daniel Kahneman

Monday, October 5, 2015

Software Craftsmanship Barcelona 2015

Last weekend I attended the Software Craftsmanship Barcelona 2015. This was the first time I participate as an attendee (I had worked in the organization of the first two editions).

It was a great event. I attended very interesting talks and had amazing conversations with many people. Some of them I already knew from the Barcelona, Zaragoza, Bilbao, Canarias and Valencia community or from abroad but many of them I just met there.

If I had to highlight my favorite talk, I'd choose Accesibilidad en el software. ¿Qué es? ¿Por qué es importante? (Software Accessibility. What is it? Why is it important?) by Juanjo


Juanjo is a great developer and an accessibility specialist. He also happens to be blind.

He showed us how he programs with Visual Studio using a screen reader and knowing nearly every keyword shortcut. It was very impressive.

Personally, I found it amazing how the human brain adapts to different situations. He has developed a great memory and is able to mentally "visualize" the code with just hearing it once (at a really fast speed).

He also told us about several applications he'd made in his spare time to improve his and another blind people's daily life.

I also enjoyed very much Vicenç García-Altés' talk about Mutation Testing, Álvaro García's talk Tu carrera como una marathon (Your career as a marathon) and the Yatzy refactoring kata also facilitated by Álvaro.
 
We (the No Flop Squad) also participated in the SCBCN15.

The afternoon before the SCBCN15 we facilitated a Pre-SCBCN15 coding dojo.

We practiced doing the Business Rules kata but with the constraint of having to develop an internal DSL that make the tests read nearly as the business rules it was testing. The constraint was based on an exercise Xavi Gost and I did to practice together in one of my last visits to Valencia. This constraint forces you to stay more time on the problem space before passing to the solution space.
We received a lot of positive feedback.

On Saturday morning we gave a talk in which we spoke about an ongoing experiment that we've been developing during the last month: Hybrid Persistence.


In this experiment, we are exploring the idea of persisting different parts of the state of an aggregate on different data storage technologies depending on the kind of state. The idea is similar to Polyglot Persistence but it works at a finer grain persisting separately the identity and mutable state of each member of the aggregate. The relationships among members of the aggregate can also be persisted independently.

The experiment is still in an initial phase, so we haven't yet reached to any sound conclusions. In the talk, we explained the ideas behind this exploration, what we have seen so far (including dead-ends, mistakes and successes) and the things we'd like to try next.

On Sunday afternoon there was an Open Space .

A session that I really enjoyed and took a lot of ideas from, was Dinamizando las comunidades locales (Energizing local communities)

in which organizers and members of several communities across Spain, shared our experiments, successes and failures in trying to improve and sustain our communities.

Also while we were selecting the open space grid, someone nominated a session asking me to give a short introduction to Clojure. Surprisingly it received enough votes to be selected so I had to improvise it.

I showed some code examples and used LightTable to write and evaluate expressions on the fly while I was explaining some language features. Álvaro helped me (thanks!) writing on Juanjo's laptop the code I was writing on my laptop and showing on the screen so that he could also follow the talk using his screen reader.

I tried to demystify parentheses and prefix notation, and explain some of the simplest goodies of the language. Even though it wasn't a good talk, I think I managed to at least arise the curiosity of some of the attendees. I also invited all to come to the Clojure Developers Barcelona's Introduction to Clojure event on next October 27th.

There were so many other interesting talks I couldn't see. I can't wait for the videos to be published.

All in all, it was a wonderful event.

I'd like to thank from here all the attendees and the organization for making it possible. I'd also like to thank Netmind for letting us use their facilities for free one more time.

Saturday, October 3, 2015

Kata: Cellular Automata in Clojure

I just did the Cellular Automata kata in Clojure.

These are the tests using Midje:

and this is the resulting code:

where I added a function print-evolution to visualize the evolution on the REPL

As usual I used a mix of TDD and REPL-driven development committing after each green and each refactoring. I also committed the REPL history.

See all the commits here if you want to follow the process.

You can find all the code on GitHub.

Friday, October 2, 2015

Interesting Talk: "One Ring to Bind Them"

I've just watched this wonderful talk by Mark McGranaghan: It contains very interesting ideas on library design.

These are the slides.

Revisiting Writing Readable Clojure code

After reading this wonderful post by Adam Bard, Writing Friendlier Clojure, I've revisited the second Clojure talk I attended to.

It was Writing Readable Clojure code by Jiří Knesl.

It impressed me and influenced my Clojure code a lot.

Monday, September 28, 2015

Kata: Integer Ranges in Clojure

I just did the Integer Ranges kata in Clojure.

These are the tests using Midje:

and this is the resulting code:

As usual I used a mix of TDD and REPL-driven development committing after each green and each refactoring. I also committed the REPL history.

See all the commits here if you want to follow the process.

You can find all the code on GitHub.

Thursday, September 24, 2015

Interesting Talk: "A Rubyist in Clojure-land"

I've just watch this great talk by David Chelimsky:

Kata: Password validation in Python

Yesterday I did the Password validation kata in Python.

I used TDD to write the code.

These are the tests using Pytest:

and this is the resulting code:



If you want to follow the process step by step, have a look at the commits.

You can find all the code in GitHub.

Wednesday, September 23, 2015

Kata: Word wrap in Clojure

Last night I did the Word Wrap kata in Clojure.

It was proposed in the last Barcelona Software Craftsmanship coding dojo but I couldn't attend, so I did it at home.

These are the tests using Midje:

and this is the resulting code:

As usual I used a mix of TDD and REPL-driven development committing after each green and each refactoring. I also committed the REPL history. See all the commits here to follow the process.

Once I got to a tail recursive solution, I tried to make it more readable by extracting some explanatory helpers and working in the naming of bindings, functions and function arguments.

You can find all the code in GitHub.

Sunday, September 20, 2015

Kata: Yatzi refactoring kata in Ruby

Last night I did the Yatzy refactoring kata in Ruby.

I mainly used it to practice with Enumerable functions.

This is the original code:

and this is the refactored one:

I committed after every small refactoring (the commits step by step).

You can find the code in this repository in GitHub.

Friday, September 11, 2015

Last Pet Project: Glowworm Swarm Optimization in Clojure

Lately I've been working bit by bit in an implementation of the Glowworm Swarm Optimization algorithm (GSO) in Clojure.

Some time ago I implemented the GSO algorithm in C++ to practice TDD.

I decided to implement it it again in Clojure to practice with something larger that Exercism exercises or katas an yet small and familiar enough to finish it in spare bits of time.

This is the code of the resulting Clojure GSO on GitHub.

This GSO Clojure version is much shorter than its C++ version.

Aside from practicing Clojure, I've learned many other things while doing it.

I'll try to enumerate them here:
  • Mixing Java and Clojure code in order to use a Sean Luke's Mersenne Twister Java implementation.
  • I learned more about Midje's checkers.
  • dire library.
  • Decomposing a bigger Clojure application in several name spaces according to roles and responsibilities.
  • Using maps to model the data.
  • Struggling to make the code more readable and keeping functions at the same level of abstraction.
  • Using only higher-order functions to compose the algorithm (I set myself the constraint to use no global configuration maps).
  • Taking advantage of those higher-order functions to test the different parts of the algorithm in isolation.
  • Separating the code that builds the graph of functions that compose the algorithm from the algorithm itself.
  • Where would I apply a library like component instead of relying only n higher-order functions.
  • Many other little Clojure things.
But overall it's been great fun.

I'd like to thank Álvaro García, Natxo Cabré and Francesc Guillén from the Clojure Developers Barcelona meetup for their feedback and Brian Jiménez for rubbing elbows with me in the first C++ version.

Wednesday, September 9, 2015

Kata: "Sieve of Eratosthenes" test-driven and explained step by step

Yesterday we practiced doing the Sieve of Eratosthenes kata at a Barcelona Software Craftsmanship event.

My partner Fernando Mora and I used TDD in Scala to write the code.

Today I did it once again in Clojure.

I'd like to explain here how I did it step by step in order to share it with the Barcelona Software Craftsmanship members.

I started by writing this test:

which I quickly got to green by just hard-coding the response:

In this first test I used wishful thinking to get the function and signature I wished.

Then I wrote the following test:

which drove me to generalize the code substituting the hard-coded list by a code that generated a list that was valid for both the first and the second test:

The next test was the first one that drove me to start eliminating multiples of a number, in this case the multiples of 2:

I made it quickly pass by using filter to only keep those that are not multiples of 2 and 2 itself:

Alternatively, I could have taken a smaller step by just eliminating 4, then go on triangulating to also eliminate 6 and finally refactor out the duplication by eliminating all the multiples of 2 that are different from 2.

Since the implementation was obvious and I could rely on filter, I decided not to follow that path and took a larger step.

I've noticed that my TDD baby steps tend to be larger in functional languages. I think the reason is, on one hand, the REPL which complements TDD by providing a faster feedback loop for triangulation and trying things out and, on the other hand, the power of sequence functions in those languages (in the case of this kata the Scala and Clojure ones).

Once the test was passing I started to refactor that ugly one-liner and got to this more readable version:

in which I extracted two helpers and used remove instead of filter to better express the idea of sieving.

My next goal was to write a test to drive me to generalize the code a bit more by eliminating the hard-coded number 2 in line 10 of the code.

To do it I just needed a test that forced the code to also eliminate just the multiples of 3:

Again I could have triangulated to first eliminate 9 and then 12 before refactoring but there was an easier way at this point: to introduce recursion.

But before doing that, I quickly went to green by calling the sieve function twice to eliminate the multiples of 2 and 3:

With this tiny step I both highlighted the recursive pattern and provided a safe place from which to start using refactoring to introduce recursion.

In this case I think that having tried to directly introduce recursion to make the test pass would have been too large a step to take, so I played safe.

Once in green again I safely refactored the code to introduce recursion:

Notice that this version of the code is the first one that solves the kata.

From this point on I just refactored the code trying to make it a bit more readable until I got to this version:

Finally, I wrote a more thorough test that made the stepping-stone tests that helped me drive the solution redundant, so I deleted them:

If you want to have a closer look at the process I followed, please check the commits list where I've also included the REPL history. You can also see all the code in this GitHub repository.

That's all.

I'd like to thank Barcelona Software Craftsmanship members for practicing together every two weeks, especially Álvaro García for facilitating this last kata, and eBay España for kindly having us yesterday (and on many previous events) in their Barcelona office.

Monday, August 31, 2015

Interesting Podcast: "Living Clojure, ClojureScript, and more with Carin Meier"

I've just listened to this very interesting ChangeLog podcast in which they interview Carin Meier:

Books I read (January - August 2015)

January
- Software Architecture for Developers, Simon Brown
- Functional Programming Patterns in Scala and Clojure, Michael Bevilacqua-Linn
- Working Effectively with Unit Tests, Jay Fields

February
- Vida y Destino (Жизнь и судьба), Vasili Grossman. (2nd time)
- Primer Libro de Lankhmar (The First Book of Lankhmar), Fritz Leiber
- Drown, Junot Díaz
- Los girasoles ciegos, Alberto Méndez
- Smalltalk Best Practice Patterns, Kent Beck

March
- Las puertas del paraiso (The Vagrants), Yiyun Li
- Growing Object-Oriented Software Guided by Tests, Steve Freeman and Nat Pryce. (2nd time)
- The Joy of Clojure, 2nd edition, Michael Fogus and Chris Houser

April
- Las ciudades carnales (Les cités charnelles), Zoé Oldenbourg
- Refactoring: Improving the Design of Existing Code, Fowler, Beck, Brant, Opdyke and Roberts. (2nd time)
- Hasta aquí hemos llegado (Τίτλοι τέλους), Petros Márkaris
- The Childhood of Jesus, J. M. Coetzee

May
- Refactoring to Patterns, Joshua Kerievsky
- You Don't Know JS: Scope & Closures, Kyle Simpson
- Ser, Ignacio Terzano
- Slow Man, J. M. Coetzee
- Número Cero (Numero Zero), Umberto Eco
- La vieja sirena, José Luis Sampedro
- The Death of Bunny Munro, Nick Cave

June
- Martha and Hanwell, Zadie Smith
- You Don't Know JS: this & Object Prototypes, Kyle Simpson
- Functional Programming for the Object-Oriented Programmer, Brian Marick

July
- Object Thinking, David West
- The RSpec Book: Behaviour Driven Development with RSpec, Cucumber, and Friends. Chelimsky, Astels, Helmkamp, North, Dennis and Hellesoy
- The Nature of Software Development: Keep It Simple, Make It Valuable, Build It Piece by Piece, Ron Jeffries
- Domain-Driven Design: Tackling Complexity in the Heart of Software, Eric Evans
- Momo, Michael Ende

August
- Los Surcos del Azar, Paco Roca
- En el pueblo del gato vampiro (Village of the Vampire Cat), Lensey Namioka (2nd time)
- El valle de los cerezos rotos (Valley of the Broken Cherry Trees), Lensey Namioka (2nd time)
- Design Patterns in Ruby, Russ Olsen
- Practical Object-Oriented Design in Ruby, Sandi Metz (2nd time)
- En el café de la juventud perdida (Dans le café de la jeunesse perdue), Patrick Modiano

Wednesday, August 26, 2015

Solving the Tire Pressure Monitoring System exercise (IV)

8. Achieving Dependency Inversion by extracting an interface.

Even though we are already injecting into Alarm the dependency on Sensor, we haven't inverted the dependency yet. Alarm still depends on a concrete implementation.

Now we'll show how to invert the dependency by extracting an interface.

Normally, it's better to defer this refactoring until you have more information, i.e., until the need for another sensor types arises, to avoid falling in the Speculative Generality code smell.

However, despite having only one type of sensor, we extract the interface anyway, as a demonstration of the refactoring technique.

So first, we rename the method that is being called on Sensor from Alarm, to make it less related with the concrete implementation of Sensor.

Then, following Kent Beck's guidelines in his Implementation Patterns book to name interface and classes, we renamed the Sensor class to TelemetryPressureSensor.

This renaming, on one hand, frees "Sensor" name so that we can use it to name the interface and, on the other hand, gives a more accurate name to the concrete implementation.

Then we extract the interface which is very easy relying on an IDE such as Eclipse or IntelliJ IDEA.

This is the generated interface:

This is Alarm's code and tests after removing any references to the pressure sensor from the naming:

Now we have a version of Alarm that is truly context independent.

We achieved context independence by inverting the dependency which makes Alarm depend on an abstraction (Sensor) instead of a concrete type (TelemetryPressureSensor) and also by moving the specificity of the SafetyRange configuration details towards its clients.

By programming to an interface we got to a loosely coupled design which now respects both DIP and OCP from SOLID.

In a dynamic language, we wouldn't have needed to extract an interface, thanks to duck typing. In that case Sensor would be a duck type and any object responding to the probe method would behave like a sensor. What we would have needed to do anyway, is the process of renaming the method called on sensor and eliminating any references to pressure from the names used inside Alarm, so that, in the end we have names that make sense for any type of sensor.

9. Using a builder for the Alarm.

Finally to make the Alarm tests a bit more readable we create a builder for the Alarm class.

That's all.

If you want to follow the whole refactoring process in more detail, I committed the code after every passing test and every refactoring. You can find the step by step commits here. The current version of the code is in this GitHub repo.

I hope this would be useful for the people who couldn't attend to the events (the SCBCN one or the Gran Canaria Ágil one)and also as a remainder for the people who could.

I'd also like to thank Luca Minudel for creating and sharing these great exercises and Álvaro García for pairing regularly with me and solved this exercise together.

This is the last post in a series of posts about solving the Tire Pressure Monitoring System exercise in Java:
  1. Solving the Tire Pressure Monitoring System exercise (I)
  2. Solving the Tire Pressure Monitoring System exercise (II)
  3. Solving the Tire Pressure Monitoring System exercise (III)
  4. Solving the Tire Pressure Monitoring System exercise (IV)

Solving the Tire Pressure Monitoring System exercise (III)

6. Improving the semantics inside Alarm and adding a new concept to enrich the domain.

Now we turn our attention to the code inside the Alarm class.

We first rename a local variable inside the check method and the method we are calling on Sensor so that we have new names that have less to do with the implementation of Sensor.

Next, we extract the condition inside the check method to an explanatory helper: isNotWithinSafetyRange.

This is the resulting code:

Notice that the Alarm class contains a data clump.

The constants LowPressureThreshold and HighPressureThreshold don't make any sense the one without the other. They together define a range, to which we have already referred both in production and test code as a safety range.

We remove the data clump by creating a new concept, the SafetyRange value object:


7. Moving Specificity Towards the Tests.

If you check the tests in AlarmShould class, you'll see that it's difficult to understand the tests at a glance.
Why is the alarm on in some cases and off in some other cases?

To understand why, we have to check Alarm's constructor in which a SafetyRange object is created. This SafetyRange is an implicit configuration of Alarm.

We can make the code clearer and more reusable by moving this configuration details towards the tests.

J. B. Rainsberger explains this concept of moving specificity towards the tests in this video which is embedded in his Demystifying the Dependency Inversion Principle post.

So we change the signature of the Alarm constructor so that the SafetyRange is injected through it.

Now the configuration detail is explicit and it's easier to understand at a glance why any test pass or not.

Moreover this change makes Alarm more reusable.

This is the third post in a series of posts about solving the Tire Pressure Monitoring System exercise in Java:
  1. Solving the Tire Pressure Monitoring System exercise (I)
  2. Solving the Tire Pressure Monitoring System exercise (II)
  3. Solving the Tire Pressure Monitoring System exercise (III)
  4. Solving the Tire Pressure Monitoring System exercise (IV)

Solving the Tire Pressure Monitoring System exercise (II)

4. Introducing a test harness.

To be able to refactor Alarm, we first need to protect its current behavior (its check method) from regressions by writing tests for it.

The implicit dependency of Alarm on Sensor makes Alarm difficult to test. However, it's the fact that Sensor returns random values that makes Alarm impossible to test because the measured pressure values it gets are not deterministic.

It seems we're trapped in a vicious circle: in order to refactor the code (improving its design without altering its behavior) we must test it first, but in order to test it, we must change it first.

We can get out of this problem by applying a dependency-breaking technique called Extract and Override call.

4.1. Extract and Override call.

This is a dependency-breaking technique from Michael Feather's Working Effectively with Legacy code book. These techniques consist of carefully making a very small modification in the production code in order to create a seam:
A seam is a place where you can alter behavior in your program without editing in that place.
The behavior we want to test is the logic in Alarm's check method. This logic is very simple, just an if condition and a mutation of a property, but as we saw its dependence on Sensor makes it untestable.

To test it, we need to alter the collaboration between Alarm and Sensor so that it becomes deterministic. That would make Alarm testable. For that we have to create a seam first.

4.1.1. Extract call to create a seam.
First, we create a seam by extracting the collaboration with Sensor to a protected method, probeValue. This step must be made with a lot of caution because we have no tests yet.

Thankfully in Java, we can rely on the IDE to do it automatically.
4.1.2. Override the call in order to isolate the logic we want to test.
Next, we take advantage of the new seam, to alter the behavior of Alarm without affecting the logic we want to test.

To do it, we create a FakeAlarm class inside the AlarmShould tests that inherits from Alarm and overrides the call to the protected probeValue method: Now using FakeAlarm we are able to write all the necessary tests for Alarm's logic (its check method):

Now that we have a test harness for Alarm in place, we'll focus on making its dependency on Sensor explicit.

5. Making the dependency on Sensor explicit.

Now our goal is to inject the dependency on Sensor into Alarm through its constructor.

To remain in the green all the time, we use the Parallel Change technique.

With TDD we drive a new constructor without touching the one already in place by writing a new behavior test with the help of a mocking library (mockito):

And we make the new test pass.

In the version of Alarm above, we also used the Parameterize Constructor technique to make the default constructor (used by FakeAlarm) depend on the new one.

Then we use the new constructor in the rest of the tests one by one in order to stop using FakeAlarm.

Once there are no test using FakeAlarm, we can delete it. This makes the default constructor become obsolete, so we delete it too.

Finally, we also inline the previously extracted probeValue method.

This is the resulting test code after introducing dependency injection in which we have also deleted the test used to drive the new constructor because we think it was redundant:

and this is the production code:

By making the dependency on Sensor explicit with dependency injection and using a mocking library we have simplified Alarm tests.

This is the second post in a series of posts about solving the Tire Pressure Monitoring System exercise in Java:
  1. Solving the Tire Pressure Monitoring System exercise (I)
  2. Solving the Tire Pressure Monitoring System exercise (II)
  3. Solving the Tire Pressure Monitoring System exercise (III)
  4. Solving the Tire Pressure Monitoring System exercise (IV)

Solving the Tire Pressure Monitoring System exercise (I)

1. Introduction.

Last week I facilitated a guided kata for a Gran Canaria Ágil event in Aplicaciones Informáticas Domingo Alonso (thanks to both for inviting me) in which I explained a possible way to solve Luca Minudel's Tire Pressure Monitoring System exercise.

This exercise is part of his TDD with Mock Objects: Design Principles and Emergent Properties exercises.

I like these exercises very much because they contain clear violations of the SOLID principles but they are sill small enough to be able to finish the refactoring in a short session at a slow pace. This makes possible to explain, answer questions and debate about design principles, dependency-breaking techniques and refactoring techniques as you apply them.

I'd like to thank Luca Minudel for creating and sharing these great exercises.

I co-facilitated this exercise with Álvaro García several month ago in a Software Craftsmanship Barcelona event and we received a lot of positive feedback.

That time, many people couldn't attend due to space limits, so I'd like to make a summary of the exercise here for them.

2. The initial code.

The initial code has two classes: Alarm and Sensor.
The exercise focuses on refactoring the Alarm class.

3. SOLID violations, hidden dependencies.

All the logic of the Alarm class is in the check method.

Alarm's main problem is that it depends on a concrete class, the sensor that measures pressure values.

This is a clear violation of the Dependency Inversion principle (DIP) which states that:
Abstractions should not depend on details.

Details should depend on abstractions.
To make things worse this dependency is hidden inside Alarm's check method (see J. B. Rainsberger's The Pain of Implicit Dependencies post).

The violation of the DIP and the implicit dependency makes also impossible to fulfill the Open Closed Principle (OCP).

Fulfilling those two principles will be one of the main goals of this refactoring.

This is the first post in a series of posts about solving the Tire Pressure Monitoring System exercise in Java:
  1. Solving the Tire Pressure Monitoring System exercise (I)
  2. Solving the Tire Pressure Monitoring System exercise (II)
  3. Solving the Tire Pressure Monitoring System exercise (III)
  4. Solving the Tire Pressure Monitoring System exercise (IV)

Sunday, August 23, 2015

Updated my A bit about JavaScript functions talk (with videos in Spanish)

Before the summer, I updated the contents of my talk about JavaScript functions to prepare a master class (that finally became two) for the wonderful Devscola project.

These are the updated slides and these are the two recorded master classes (in Spanish):
I hope you'll find them useful.

Interesting Podcast: "Functional and Object Oriented Programming with Jessica Kerr"

I've just listened this great Ruby Rogues podcast with Jessica Kerr talking about functional and object oriented programming:

Interesting Podcast: "Growing Object Oriented Software Guided by Tests with Steve Freeman and Nat Pryce"

I've just listened this great Ruby Rogues podcast with Steve Freeman and Nat Pryce talking about their wonderful book Growing Object Oriented Software Guided by Tests:

Wednesday, August 5, 2015

Contract tests for interfaces discovered through TDD

We were working through the following iterations of an exercise:

First iteration
A user can register with a user name.

For instance: @foolano

If anyone else has already registered with that name there is an error.

Second iteration
A user can follow another users.

To do so it's only required to know the user name of the user to be followed.

Anyone can query the followers of any given user just knowing its user name.

Third iteration
The registered users and their followers must be persisted.
(source: Diseño modular dirigido por pruebas workshop at PyConEs 2014)

We produced several application services for this features that at some point collaborated with a users repository that we hadn't yet created so we mocked it in their specs.

In these tests, every time we allow or expect a method call on our repository double, we are defining not only the messages that the users repository can respond to (its public interface) but also what its clients expect from each of those messages, i.e. its contract.

In other words, at the same time we were testing the application services, we defined from the point of view of its clients the responsibilities that the users repository should be accountable for.

The users repository is at the boundary of our domain.

It's a port that allows us to not have to know anything about how users are stored, found, etc. This way we are able to just focus on what its clients want it to do for them, i.e., its responsibilities.

This results in more stable interfaces. As I heard Sandi Metz say once:

"You can trade the unpredictability of what others do for the constancy of what you want."

which is a very nice way to explain the "Program to an interface, not an implementation" design principle.

How those responsibilities are carried out is something that each different implementation (or adapter) of the users repository must be responsible of.

However, the terms of the contract that its clients rely on, must be respected by all of the adapters.

In this sense, any adapter must be substitutable by any other without the clients being affected, (yes, you're right, it's the Liskov substitution principle).

The only way to ensure this substitutability is by testing each new adapter to see if it also respects the terms of the contract.

This is related to J. B. Rainsberger's idea of contract tests mentioned in his Integrated Tests Are A Scam talk and in his great TDD course, and also to Jason Gorman's idea of polymorphic testing.

Ok, but how can we test that all the possible implementations of the user repository respect the contract without repeating a bunch of tests?

This is one way to do it in Ruby using RSpec.

We created a RSpec shared example in a file named users_repository_contract.rb where we wrote the tests that characterize the behavior that users repository clients were relying on:

Then for each implementation of the users repository you just need to include the contract using RSpec it_behaves_like method, as shown in the following two implementations:

You could still add any other test that only had to do with a given implementation in its spec.

This solution is both very readable and reduces a lot of duplication in the tests.

However, the idea of contract tests is not only important from the point of view of testing.

In dynamic languages, such as Ruby, they also serve as a mean to highlight and document the role of duck types that might otherwise go unnoticed.

Kata: Print Diamond in Clojure

Yesterday we did the Print Diamond kata in the Clojure Developers Barcelona group.

I paired with Rafa Gómez. We managed to complete a recursive solution to the problem using our usual mix of TDD and REPL-driven development.

Later, we showed our solution and realize that, even though, it worked fine, we had to improve the names of some helper functions we had created to make our solution easier to understand.

After that, Samuel Lê, presented on the whiteboard (we couldn't connect his laptop to the projector) a completely different and very elegant approach.

I'll try to explain it:

Say, for instance, that you're trying to create the diamond for D.

You first create the following sequence repeating the string "DCBABCD" as many times as lines there are in the diamond:

Only one letter is allowed to appear in each line of the diamond.

Let's represent this in a table:

Now the only thing we have to do to get the correct diamond lines is to substitute by a space (we used an underscore to make it easier to visualize) every letter of the line that is different from the allowed letter for that line:

This is a very elegant approach that only uses sequences functions.

When I got back home I redid the kata again using both approaches: the recursive one and the one that Samuel had explained on the whiteboard.

These are the tests I used to test drive the recursive code (sorry I can't show the REPL history because I haven't found where Cursive saves it):

I'm using an underscore instead of a space to make the results easier to visualize.

This is the recursive code:

Then I deleted the recursive code and started playing in the REPL to build a new solution following Samuel's approach and using the previous tests as acceptance tests to know when I was done.

Once I had it working again:

I refactored the code a bit introducing some helpers to separate responsibilities and make the code more readable and renamed some bindings.

This is the resulting code:

You can find all the code in this GitHub repository.

As usual the Clojure meetup and the conversations having a drink afterwards have been both great fun and very interesting.

We also met Alejandro Gómez which is writing this great ClojureScript book and has recently moved to Barcelona.

Tuesday, July 28, 2015

Using pattern matching in the Binary Search Tree Clojure solution

A member of SCBCN coded a beautiful solution in F# for the Binary Search Tree kata.

I wanted to try using pattern matching to get to a similar solution in Clojure.

So I watched Sean Johnson's Pattern Matching in Clojure talk and read a bit the documentation of clojure/core.match.

My intention was to use defrecord matching, but I couldn't make it work.

Later I found out in an answer to this StackOverflow question, Pattern matching on records in Clojure, that this feature hadn't been implemented yet.

So I followed the advice given in StackOverflow of using map pattern matching and coded this version of the Binary Search Tree:

Even though is not as nice as the F# one, it reads very well and allowed me to get rid of the value, left and right private helpers and all ifs.

Then I tried another thing that Sean Johnson had mentioned in his talk.

I coded another Binary Search Tree solution using the defun macro which creates functions with pattern matching like in Erlang, or Elixir

This is the resulting code using defun:

which also reads very nice.

Sunday, July 26, 2015

Applying property-based testing on my binary search tree implementation

Some weeks ago I did the the Binary Search Tree problem from Exercism in Clojure.

I used TDD using some of the sample tests that Exercism provided and some other that I added.

These were the tests, after deleting some redundant ones:

And this was the binary search tree code:

I was just testing a few cases.

To gain confidence in my solution and play a bit more with the exercise, I decided to apply a bit of property-based testing on it.

So I added the clojure/test.check dependency to my project:

and added a new spec to the tests:

The in-order-traversal-of-bst-sorts-elements spec is checking the in-order-traversal-of-bst-sorts-elements-property 100 times.

For each check, the generator creates a random vector of integers and checks if the result of calling in-order on the binary search tree created from the vector is equal to the sorted vector.

The macro clojure.test.check.clojure-test/defspec allows to integrate clojure/test.check with clojure.test, so that properties can run under the clojure.test runner.

Midje, the test framework I'm using, can also detect and run clojure.test tests.

Ok, after running the tests, this is what I got (formatted so it fits without a lot of scrolling):

There was a case that was failing.

A really nice thing about clojure/test.check is that it tells you the smallest case that makes your code fail. See the value of the :smallest key inside the map associated to the :shrunk key of the map in the output.

I had forgotten to write a test for the empty vector!

So I added a new failing test for that case:

and modified the code to make it pass:

Now the tests were all passing:

At this moment, I could have deleted all the unit tests and kept only the property-based ones, because the former were now redundant.

I chose not to do it, because I really like the readability of midje's facts.

In this case, I've used property-based testing to thoroughly check my solution after I had finished doing TDD. I wasn't wearing the TDD hat when I used it, I was just doing testing.

I think property-based testing and TDD can complement each other very nicely.

Another way to combine property-based testing and TDD is using the capability of clojure/test.check of giving you the smallest case that fails to help you choose the next test to drive your code.

Jan Stępień talked about this in his talk in last EuroClojure conference:
Another thing to consider is that the smallest case that makes the code fail given by property-based testing may not always correspond to the test that allows the code to grow in a small and easy to implement step.

I think that chances are that many times it might be, though.

Another thing to explore :)

Interesting Talk: "Interaction Driven Design"

I've just watched this great talk by Sandro Mancuso: This is an update and enhanced version of his previous talk: Crafted Design.

Wednesday, July 22, 2015

Kata: Binary Search Tree in Ruby

Yesterday in the Barcelona Software Craftsmanship coding dojo we did the Binary Search Tree kata.

Raúl Lorca and I paired using TDD in C# to get to a pretty OO solution.

We didn't finish the exercise. We got to create the binary search tree but we didn't have time to code the in-order depth-first traversal.

Well, it doesn't matter. The important thing is that we practiced TDD, recursion and OO by test-driving a recursive data structure.

Today, with a bit more of time, I did the the whole kata in Ruby.

These are the resulting tests, after deleting some I used as scaffolding to get to the final version of the code (check the commits if you want to see the evolution of the tests):

And this is the final version of the code:

To document the whole TDD process I committed the code after every passing test and every refactoring.

You can check the commits step by step here and all the code in this repository in GitHub.

I had done the same exercise in Clojure several weeks ago as part of the Exercism problems. Compare the code there with this one if you like.

Tuesday, July 14, 2015

Exercism: "Largest Series Product in Clojure"

I solved the Largest Series Product problem in Clojure.

This is my solution:

This Exercism problem is based on a Project Euler's exercise I solved some time ago.

You can nitpick my solution here and/or see all the exercises I've done so far in this repository.

Wednesday, July 8, 2015

Exercism: "Difference Of Squares in Clojure"

I solved the Difference Of Squares problem in Clojure.

This exercise was very easy.

I played with partial and the thread last macro (->>) to try to make the solution more readable:

It turns out that I had done this exercise before.
You can see that version in Euler Project: Problem 6 in Clojure

You can nitpick my solution here and/or see all the exercises I've done so far in this repository.

Sunday, July 5, 2015

Exercism: "Binary Search Tree in Clojure"

I solved the Binary Search Tree problem in Clojure.

I wrote three versions of the to-list function which makes a depth-first traversal of the tree returning the sequence of visited values.

This is my first version:

This is the second one using concat:

And the last one using the tree-seq function that I discovered looking at other solutions in Exercism: You can nitpick my solutions here and/or see all the exercises I've done so far in this repository.

Saturday, July 4, 2015

Exercism: "Accumulate in Clojure"

I solved the Accummulate problem in Clojure.

This is an easy one in Clojure, the only restriction is that you can't use map.

I did 3 versions to practice:

A recursive one:

Another one using reduce:

And another one using a sequence comprehension: You can nitpick the solutions here and/or see all the exercises I've done so far in this repository.

Friday, June 5, 2015

Interesting Talk: "Eliminate JavaScript Code Smells"

I've just watched this very interesting talk by Elijah Manor: This is the short version of the talk, in which he talks about half the code smells that appear in the long version.

It seems that the long version of the talk hasn't been recorded yet (or so it says here).

In any case, these are the slides of the long version talk,

Wednesday, June 3, 2015

Monday, June 1, 2015

Interesting Paper: "Mock Roles, not Objects"

I've just read this very interesting paper by Steve Freeman, Nat Pryce, Tim Mackinnon and Joe Walnes about mock objects as a design technique for identifying types in a system based on the roles the objects play: They talk about the importance of RDD, the Law of Demeter and Tell Don't Ask in this technique and how it can lead to an OO style based in composition rather than inheritance, encouraging designs with good separation of concerns and modularity.

It also gives many heuristics to help drive your design using mock objects and fights against some typical misconceptions surrounding mock objects.

Interesting Podcast: "Hexagonal Rails with Matt Wynne and Kevin Rutherford"

I've just listened this great Ruby Rogues podcast with Matt Wynne and Kevin Rutherford:

Wednesday, May 20, 2015

Exercism: "Queen Attack in Clojure"

I solved the Queen Attack problem in Clojure.

This is my solution:

I think that the can-attack function should be called can-attack?. I've kept its original name because it's being exercised from the tests given by Exercism.

You can nitpick the solution here and/or see all the exercises I've done so far in this repository.

Exercism: "Robot Simulator in Clojure"

I solved the Robot Simulator problem in Clojure.

This is my solution:

I think that the turn-right and turn-left functions aren't necessary. I've kept them because they are being exercised from the tests given by Exercism.

You can nitpick the solution here and/or see all the exercises I've done so far in this repository.

Tuesday, May 19, 2015

Exercism: "Kindergarten Garden in Clojure"

I solved the Kindergarten Garden problem in Clojure.

This is my solution:

You can nitpick this solution here and/or see all the exercises I've done so far in this repository.

Saturday, May 16, 2015

Exercism: "Crypto Square in Clojure"

I solved the Crypto Square problem in Clojure.

This is my solution:

You can nitpick this solution here or see all the exercises I've done so far in this repository.

Friday, May 8, 2015

Tuesday, May 5, 2015

Kata: String Calculator in Clojure

Last week we started working on the String Calculator kata at the Clojure Developers Barcelona meetup.

Finally, this week I found some time to finish it.

These are the tests using Midje:

The resulting code which is divided in several name spaces.

The string-calculator.core name space:

The string-calculator.numbers-parser which is where most of the logic lives:

The string-calculator.numbers-validation name space:

Finally, the string-calculator.numbers-filter name space:

I used a mix of TDD and REPL-driven development to code it.

To document the process I committed the code after every passing test and every refactoring.

This time I didn't commit the REPL history because I used Cursive and I didn't find how to save it. Apart from that, I really enjoyed the experience of using Cursive.

You can find the commits step by step here and the code in this repository in GitHub.

Thursday, April 30, 2015

Interesting Talk: "Developing ClojureScript With Figwheel"

I've just watched this wonderful talk by Bruce Hauman:

Books I read (January - April 2015)

January
- Software Architecture for Developers, Simon Brown
- Functional Programming Patterns in Scala and Clojure, Michael Bevilacqua-Linn
- Working Effectively with Unit Tests, Jay Fields

February
- Vida y Destino (Жизнь и судьба), Vasili Grossman. (2nd time)
- Primer Libro de Lankhmar (The First Book of Lankhmar), Fritz Leiber
- Drown, Junot Díaz
- Los girasoles ciegos, Alberto Méndez
- Smalltalk Best Practice Patterns, Kent Beck

March
- Las puertas del paraiso (The Vagrants), Yiyun Li
- Growing Object-Oriented Software Guided by Tests, Steve Freeman and Nat Pryce. (2nd time)
- The Joy of Clojure, 2nd edition, Michael Fogus and Chris Houser

April
- Las ciudades carnales (Les cités charnelles), Zoé Oldenbourg
- Refactoring: Improving the Design of Existing Code, Fowler, Beck, Brant, Opdyke and Roberts. (2nd time)
- Hasta aquí hemos llegado (Τίτλοι τέλους), Petros Márkaris
- The Childhood of Jesus, J. M. Coetzee

Interesting Talk: "The Art of the Javascript Metaobject Protocol"

I've jut watched this great talk by Reginald Braithwaite:

Clojure Developers Barcelona: Short talk about sequence comprehensions

Last Tuesday I gave a short talk about sequence comprehensions in Clojure for some of the Clojure Developers Barcelona study group members.

This is the "clean version" of the code I wrote on Lightable to explain it:

As usual I had a great time and learned a lot preparing this talk.

After the talk, we talked about topics we'd like to learn about in the next months and the started to practice in pairs programming the String Calculator kata.

Thanks all for coming!

Saturday, April 18, 2015

Kata: Gilded Rose in Clojure (III) -> Updating conjured items by decoration

After the two previous posts (Clarifying conditional logic and Replacing conditional with polymorphism using multimethods), I had this version of the code:

that was being used from the gilded-rose.core name space:

Then I started introducing the new conjured items functionality using TDD.

These are the new tests for conjured items:

and these is the resulting code of the gilded-rose.item-quality name space:

Notice the change in the update multimethod dispatch function. Now instead of being :name as before, it's the function type-of-item that returns the dispatch value :conjured if the item is a conjured one (i. e., if its name contains "Conjured"), or the type of item corresponding to each item name otherwise (which it looks up in the item-types-by-name map).

I also added a defmethod for the :conjured dispatch values which decorates update by calling it twice passing the not conjured version of the item and modified the other defmethod functions to use the type of item instead of its name. This made possible a better way of removing the duplication for regular items than the previous update-regular-item-quality private function.

This simple decoration made all the tests shown before pass, except the "Conjured Sulfuras is still immutable" one. For this test to pass I had to modify the degradable-item? query in the gilded-rose.core name space:

That's all. You can follow the whole process I've just described having a look at the commits I did after every small refactoring (look at commits from Conjured items quality decreases by two each day before sell date on)

Starting from the polymorphic version of update, we had got through refactoring, made it easy to add the new conjured items functionality as a decoration of update.

Compare this Clojure version of Gilded Rose with the Java version I did some time ago.

This is the last post in this series about the Gilded Rose kata in Clojure:
  1. Clarifying conditional logic
  2. Replacing conditional with polymorphism using multimethods
  3. Updating conjured items by decoration

Kata: Gilded Rose in Clojure (II) -> Replacing conditional with polymorphism using multimethods

At the end of the previous post (Clarifying conditional logic), I had this version of the code:

Even though the conditional logic in the update-item-quality function read much better than the original one, I completely got rid of it using the replace conditional with polymorphism refactoring. I used multimethods which is one of the ways of achieving polymorphism in Clojure.

To start this refactoring, I first renamed the update-item-quality function to update-item-quality-old. Then I created a multimethod called update-item-quality with :name as dispatch function and with a method associated to its default dispatch that called the update-item-quality-old function:

This new version behaved exactly like the previous one and it was a good base to do the refactoring in small steps (one branch at a time) because every dispatch value not associated yet with a function was calling the old code thanks to the default dispatch.

Next I wrote a defmethod associated to the Age Brie item, copied the code from the Age Brie branch in update-item-quality-old into it and deleted the branch and the aged-brie? query helper. After this change all the tests were still passing.

Then I continued eliminating the rest of the branches in the cond of the update-item-quality-old function and their associated query functions.

Once I finished wit all the branches, I had replaced the conditional with polymorphism and could safely delete update-item-quality-old. I also changed the method associated with the default dispatch to make it just returned the received item (this was what got executed for the Sulfuras item and it corresponded to the :else branch of the cond in the old code).

To finish the refactoring I extracted the update-regular-item-quality helper to remove some duplication in some defmethods and moved the code that updated the quality into a separate name space, gilded-rose.item-quality:

You can follow the whole process I've just described having a look at the commits I did after every small refactoring (look at commits between Introduced a multimethod which now it's defaulting to the old update item quality function and Added helper to make all items age one day)

After this refactoring I had a nice polymorphic solution that made it easier to add the new conjured items functionality.

The next and last post will show how I modified the multimethod dispatch function to decorate the update quality behavior when it was updating a conjured item.

This is the second post in a series of posts about the Gilded Rose kata in Clojure:
  1. Clarifying conditional logic
  2. Replacing conditional with polymorphism using multimethods
  3. Updating conjured items by decoration