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.