We had a kind of duplication in our tests that we didn't know how to deal with. The refactoring "Introduce Polymorphic Creation with Factory Method" explained by Joshua Kerievsky in his brilliant book "Refactoring to Patterns" gave me the solution to avoid duplicated tests.

  1. [TestFixture] public class
  2. ChangingColorWithImplicitExclusionsShould : ConfigurationTests {
  3. [Test] public void
  4. not_allow_change_when_its_compulsory_has_the_same_family_than_a_configured_equipment() {
  5. CatalogBuilder
  6. .AddEquipmentWithFamily("PR1", "Radio")
  7. .AddEquipmentWithFamily("PR2", "Radio")
  8. .AddColor("red", WithEquipmentsCompulsory("PR2"));
  9. var configuration = Agiven.ModelConfiguration()
  10. .With(Agiven.ConfigEquipment("PR1"))
  11. .Build();
  12.  
  13. Expect.CallTo(() => ExecuteChangeColor("red", configuration))
  14. .ToThrow<EquipmentsWithSameFamilyException>();
  15. }
  16. }
  17.  
  18. [TestFixture] public class
  19. ChangingInteriorWithImplicitExclusionsShould : ConfigurationTests {
  20. [Test] public void
  21. not_allow_change_when_its_compulsory_has_the_same_family_than_a_configured_equipment() {
  22. CatalogBuilder
  23. .AddEquipmentWithFamily("PR1", "Radio")
  24. .AddEquipmentWithFamily("PR2", "Radio")
  25. .AddInterior("xyz", WithEquipmentsCompulsory("PR2"));
  26. var configuration = Agiven.ModelConfiguration()
  27. .With(Agiven.ConfigEquipment("PR1"))
  28. .Build();
  29.  
  30. Expect.CallTo(() => ExecuteChangeInterior("xyz", configuration))
  31. .ToThrow<EquipmentsWithSameFamilyException>();
  32. }
  33. }
  34.  

Tests are very similar, the differences are in lines 8 and 25, and also in lines 13 and 30. First tests tries to change the color of a configuration whereas the second one tries the interior. Part of the handling business logic is the same. This is just one scenario but we had many of them, with same expected behavior for color, interior, equipment, and more. Eventually there was a lot of "duplication".

After refactoring, we have a base abstract class with the tests, exposing template methods that child classes have to implement in order to populate the catalog and also to execute the corresponding action:

  1. [TestFixture] public abstract class
  2. CantChangeConfigurationBecauseThereisImplicitExclusionWhen : ConfigurationTests {
  3. [Test] public void
  4. its_compulsory_has_the_same_family_than_a_configured_equipment() {
  5. CatalogBuilder
  6. .AddEquipmentWithFamily("PR1", "Radio")
  7. .AddEquipmentWithFamily("PR2", "Radio");
  8. AddImplicitExclusionItemWithCompulsories("PR2");
  9. var configuration = Agiven.ModelConfiguration()
  10. .With(Agiven.ConfigEquipment("PR1"))
  11. .Build();
  12.  
  13. Expect.CallTo(ChooseConflictiveItem(configuration))
  14. .ToThrow<EquipmentsWithSameFamilyException>();
  15. }
  16.  
  17. protected abstract void AddImplicitExclusionItem(string code);
  18. protected abstract Func<ModelConfiguration> ChooseConflictiveItem(ModelConfiguration configuration);
  19. }
  20.  
  21. [TestFixture] public class
  22. ChangingColor : CantChangeConfigurationBecauseThereisImplicitExclusionWhen
  23. private const string itemCode = "irrelevant";
  24.  
  25. protected override void AddImplicitExclusionItem(string code){
  26. CatalogBuilder
  27. .AddColor(itemCode, WithEquipmentsCompulsory(code));
  28. }
  29.  
  30. protected override Func<ModelConfiguration> ChooseConflictiveItem(ModelConfiguration configuration){
  31. return () => ExecuteChangeColor(itemCode, configuration);
  32. }
  33. }
  34.  

The base class "ConfigurationTests" contains just helper methods such as ExecuteChangeColor, or ExecuteChangeInterior, but no tests at all. Otherwise tests would run twice.

When it comes to refactoring, my preferred katas consist of experimentation with the actual code base I am working on. I just create a new branch from a certain commit, play with several refactorings and then throw it away. I usually end up with several experimental branches starting from the same commit. Sometimes if I end up with a better design, I apply the changes to the default or master branch, but that is not the goal. The goal is to improve my refactoring and design skills.

Pretty much every day, as I am coding, I find out slices of the code that smell. I find out room for a better design. However, if the code is working fine, I mean, if there are no known defects, if there is no real need to change, it's probably not worth spending work time to refactor it. At least not now. But I do write down a note about the smell to think about it later. This note often becomes the subject of the code kata.

When you approach your code base as a code kata, you don't have to care about time, you can just spend as much time as you want enjoying and learning. That code deals with a degree of complexity that is often hard to find in code katas. It's a real challenge. A big chance to improve your skills. The fact that I can experiment without any pressure, sometimes lead me to much better designs that the code base end up benefiting from. Eventually it's also good for my customers and colleagues.

Try it out and let me know whether you find it useful 😉

Usually IT books don't age very well, things change very fast in the sector. This is specially true of books on particular tools, libraries, frameworks... but even books about methods and techniques require critical thinking when studying them. If the book is 5 or 10 years old, it's very likely that the author himself doesn't code the way he described in his book. We evolve as programmers - hopefully. However that doesn't mean that the book is no longer valuable. Many things are still valuable for sure, we just have to figure out what slices are useful today given our current context. Reasoning may be different if the programming language is not the same you use today, or even if its version is not the same. The paradigm may be different as well. Tools change and evolve very fast so unit tests written today, with all the fancy assertion libraries we have plus all the modern features of xUnit frameworks,  have to be very different to the unit tests you can find in a book written a decade ago.

I am currently reading a classic book, a great one from Martin Fowler Signature series - not written by Martin though. The book is terrific, I wander why didn't I read it then years ago! I am getting a lot of value from it, but I also notice certain old fashion techniques with well-known downsides.

I wrote a book on TDD 6 years ago. Since then my programming style has changed quite a lot. The way I do TDD today is different, and there are certain examples in the book that I even consider anti-patterns. I don't know when will I be able to rewrite it, although I wish, but the reality is that time flies.

Consider the age and context of books, don't just assume everything is valid today

cas2015

No habia participado en una Conferencia Agile Spain desde el 2010 que fué en Madrid, la primera. En aquel entonces iba ilusionado con 50 ejemplares en mi maleta de nuestro flamante libro de TDD, que colocamos en el stand de Plain Concepts porque amablemente me brindaron su espacio y hasta los vendían ellos. Plain aun era una empresa pequeña. Mi segundo arranque como autónomo había sido a penas un año atrás, antes del AOS 2009, primer gran evento de la comunidad, tambien en Madrid. Llevaba la ilusión de ver a todos aquellos nuevos amigos que había conocido en el AOS. No diré nombres para no dejarme a nadie fuera.

Después de aquella CAS, la avalancha de trabajo y la gran cantidad de viajes de avión que ello implica, hizo que tuviese menos disponibilidad. Me esforcé por conocer otras conferencias y otras comunidades. Quería salir por Europa y estuve en conferencias en Berlin y Londres. Y así los años han volado hasta llegar a CAS 2015. De nuevo en Madrid, la ciudad de las oportunidades para mí. Este año no podíamos faltar, teníamos que apoyar y de hecho es la primera vez que patrocinamos un evento de la comunidad. Estamos muy orgullosos de haber patrocinado, para nosotros es poner un granito de arena para que haya sido posible, aunque si no hubiesemos sido nosotros, había patrocinadores en cola, ... ¡qué éxito!

La organización de la conferencia ha sido brillante, para quitarse el sombrero. Los que me conocen saben que soy sincero, no lo diría si no lo pensase. Todo el equipo de organización y voluntarios se ha dejado la piel para que disfrutásemos. Me asombra especialmente lo tranquilos y confiados que veía a Alberto, Tino, Rubén, Vanesa, Gonzalo y Javier a pesar del monstruo que habían montado, un evento con 700 personas. Me resolvieron todos los contratiempos de última hora y me permitieron hacer la charleta de apertura cuando Javier Acero causó baja por su lesión de rodilla. Y debo decir que me lo pasé muy bien preparando la charla y luego sobre el escenario.

Desde hace unos años no me apetece dar charlas sino que prefiero formatos interactivos en plan taller donde podemos mantener conversaciones. Es porque no siento que aporte tanto valor con un monólogo durante tanto tiempo, no creo sinceramente que tenga cosas tan importantes que decir, creo que es más importante la sinergia que surge de la conversación. Pero en esta ocasión tenía que ser charla forzosamente así que como no me apetecía meter una chapa, quise que la gente se echase unas risas y se diviertiese, por lo que me propuse ensayar un baile y hacer un poco el payaso en el escenario. Pensé que sería una buena forma de abrir el día. Gracias a que Autentia lo grabó todo, queda ahí para los curiosos 😀

Había tanta gente que no pude hablar con muchos amigos, a penas pude decirles "hola" y a otros ni eso. Es lo que ocurre cuando el evento es masivo. Durante los breaks de comida y café, si me movía a buscar bebida me encontraba a gente por el camino y ya no volvía al sitio, dejaba las conversaciones a medias por más que no quisiera, una pasada. Un chute de socialización a los bestia, a lo loco. Conocí y "desvirtualice" a gente pero no nos dió tiempo a profundizar. Sabor agridulce por ese lado.
No pude asistir a las charlas que hubiese querido, de hecho practicamente no pude elegir charla pero por suerte estan grabadas.

Es muy bonito ver cómo han crecido durante estos años, profesionales de la comunidad a la que tuve la suerte de conocer en algunos de mis cursos y conferencias durante 2009, 2010, 2011... Hoy en día tengo ganas de visitarles y de trabajar con ellos porque tienen muchísimo que enseñarme. Esto es un éxito de la comunidad. Habiendome movido por otras comunidades de práctica en Europa sé que no tenemos nada que envidiar. Estamos a la altura para compartir con ellos lo que sabemos.

En cierto modo tengo la sensación de que la CAS se está distanciando del desarrollo de software, pero no me atrevería a decir si eso es bueno o malo. El taller de Tim Ingarfield y Diego Rojas fue para mi oro puro, me encantó estar allí y lo volveré a ver en video. Son unos genios. Me aportó muchísimo valor.
De alguna manera me gustaría que no nos olvidásemos de que una de las ideas de "Agile" cuando nació era acercar a gerentes y a técnicos, alinearnos todos. Y a veces tengo una sensación de que el trabajo técnico no está igual de valorado que la gestión de proyectos. Yo valoro mucho la gestion del proyecto, el cuidado de las personas, las dinámicas de equipos, la facilitación como via para quitar impedimentos... y necesito que tambien valoremos nuestro trabajo técnico. Que no se olvide que la calidad del software es tan importante como la calidad de las relaciones humanas. Que no se piense que para hacer carrera hay que dejar de programar y saltar a la gestión, sino que los que disfrutan de programar puedan hacer carrera como profesionales de la programación en sus empresas.
Me gustaría que la gente que fuese a la CAS no se fuese de allí sin saber por ejemplo que el método original se llama Extreme Programming y que estaba basado en unos valores y unos principios. Volver a recordar la raíz.
Dudo que sea buena idea que futuras ediciones de CAS sean incluso más grandes, ya me ha parecido que esta edición era gigantesca. Me pregunto, ¿por qué algunas personas hablaban de crecer en magnitud con cada edición futura, ¿qué tendría eso de bueno?
Crecer por crecer, no tiene por que ser bueno. Se me quedó grabada una idea de Joan Antoni Melé en una charla suya que vi hace tiempo donde comparaba a empresas cuyo objetivo era crecer por crecer, con un cáncer .

La keynote de Leo tuvo un fondo que me gustó mucho, el de no ser dogmaticos. Al menos eso entendí yo y me gusta porque el sentido común y el pragmatismo debe primar sobre los procesos y normas establecidos. Pero sus formas me parecieron agresivas y quizás un poco contraproducentes. Me pareció ofensiva la foto de "Manolo y Benito" cuando habló del movimiento de la artesanía del software, porque ese movimiento está buscando que se reconozca la importancia del trabajo técnico, al mismo nivel que se reconoce una buena gestión y facilitación. Ni más ni menos.
Tanto en su keynote como en alguna otra charla creí entender que se hablaba de programadores que se recrean más de la cuenta tratando de hacer florituras en el código. Creo que Artola dijo poeta del código. Bien, en mi experiencia, jamás he visitado una empresa o equipo donde pecasen de exceso de refactoring o de exceso de pair programming o mob programming. Si entendemos el refactoring por hacer el código existente, más legible y fácil de mantener y NO por un rediseño, entonces de veras que nunca he visto a nadie pecar de exceso de refactoring. El refactoring siempre se hace de menos, nunca de más. Yo recomiendo media horita de refactoring al dia, igual que el médigo recomiendo caminar media hora al día. Para que luego no haya que dedicar dias o semanas a intentar poner orden cuando está ya todo desordenado y sucio.
Lo que sí me suelo encontrar es sobreingeniería, hacer diseños de software demasiado grandes y complejos, arquitecturas gigantescas que no hacen falta. Y tambien veo gente invirtiendo tiempo en frameworks, librerías y otras herramientas, que luego no tiene un retorno de inversión. A veces se eligen porque parecen muy chulas, porque son modernas y acaban costando una fortuna. A veces esas herramientas se escogen para suplir lo que en realidad debería ser una arquitectura adaptada a las necesidades concretas del proyecto y esa falta de diseño se convierte en un cuello de botella con un coste matador.
El legendario Joshua Kerievsky en su libro "Refactoring to Patterns" habla de "underengineering" y de "overengineering". Técnicas como refactoring a diario y pair programming a diario ayudan a mitigar el riesgo de la infraingeniería y la sobreingeniería. Pero nadie dice que hay que estar todo el dia refactorizando ni todo el dia en pair programming! Uselo usted con sentido común!

En cierta forma me parece que algunos mensajes que se transmitieron pueden resultar muy confusos para los que no tienen suficiente bagaje. Me dió la impresión que echan por tierra parte del trabajo de reeducación y formación que hacemos en las empresas y en los equipos. Para mí el tema de fondo era clave y necesario pero las formas, arriesgadas.

He tenido profundas conversaciones con viejos y sabios amigos durante las cenas y el networking, que junto con el resto del evento me han hecho darme cuenta de lo mucho que la comunidad me apoya y me quiere. Pese a lo zoquete que he sido en varias ocasiones. Ver que ellos se quedan con lo bueno de uno y que son tan tolerantes con los defectos, me ha impactado. Me doy cuenta que la comunidad agile spain es un lugar donde crecer seguro, personal y profesionalmente, un sitio donde te permiten que te equivoques, que rectifiques, que cambies... y donde te apoyan a pesar de los fallos. Y esto es porque se trata de gente lista y madura. Estas conversaciones, esta revelación me está haciendo crecer. Me doy cuenta de que quiero aprender a comunicarme de forma no violenta. Que no quiero que mis malas formas estropeen el mensaje que quiero transmitir porque hieren a las personas y no ayudan a llegar a la meta, a ningún sitio. Sirva como ejemplo de lo que no quiero hacer, mi bronca con @semurat y @david_bonilla hace tiempo en twitter o mi bronca en el AOS de Tenerife.

Con esta comunidad y el apoyo incondicional de nuestro gran equipo CB&A, puedo prograsar cada día en constante mejora contínua. Podemos crecer juntos. Es un lujazo trabajar en un equipo donde, cuando te enteras que ha surgido cualquier problema ya tienes a un compañero trabajando en ello. No tienes que decirle a nadie que recoja los rollouts al terminar evento, cuando llega la hora de salir aparece Modesto con ellos al hombro. No tienes que pedirle a Alfredo que te traiga unas gafas para hacer el payaso, cuando llega la hora aparece con unas espectaculares. No tienes que pedirle a Luis que busque y hable con clientes nuestros que estaban allí en la CAS para pregunterles cómo les va, sino que cuando nos reunimos por la noche ya trae ya un resumen detallado de cada uno, con ideas y propuestas para ayudarles. No hace falta pedir feedback sincero, Nestor y Juan te lo dan así sea para ponerte en tu sitio. Fran se curró la landing page del evento por las noches aunque no pudiese venir.
Zazu estuvo ayudandome a maquetar las slides y el guión de mi presentación en todo momento.
La ilusión, las ganas y la sonrisa de nuestros aprendices, Ronny, Miguel y Dani son contagiosas fuentes de inspiración y motivación.

Gracias a todos los que han hecho posible la CAS2015, enhorabuena por conseguirlo.

Dejo por aqui las slides, ya actualizo el post con videos cuando se publiquen:

CAS2015 Opening - Improving the Software from Carlos Ble

So your pair is proposing a route or plan that you don't agree on. Am talking about a refactoring, a redesign or just the way to test drive the next feature. You have told him your reasons no to agree with him and there is no way to get to an agreement. It's perhaps frustrating because you believe his strategy will fail but he definitely wants to proceed that way. What do you do? Argue forever?

I don't think you have to always agree on the path you are going to walk. The important thing is that both understand the plan so that driver and navigator can help each other get there. In those situations I end up saying... I believe this approach is not the best and I would try out something else - something I explained already... but anyway, I'll help you with your idea, let's do it.

Several times my pairs have proven that they were right and the plan was effective. Some other times it wasn't a good idea, but we built a trustworthy relationship, a supportive one.

Learning with Peter

Last week I was lucky to host my good friend Peter Kofler in his visit to Gran Canaria, where he came to facilitate the Glodal Day of Code Retreat and also to work together a couple of days in our biggest project at the moment.

We've been working in the same project for a year now, our team joined the client's team to play several roles, from mentoring to developing features ourselves. Peter's visit was a fantastic learning experience and also a way to bring back principles that wear out as we face recurring issues over time. Even though we started as external consultants, the fact that we've been a year immerse in the project sometimes leading the development ourselves, changes our vision and focus. Peter's fresh vision reminded me of myself a year ago, when the gig started and reinforced my willingness to stick with my principles. Thank you Peter!

Notes that I wrote down during working sessions:

  • Code metrics is exactly what we need now to show everyone the health of the code base. We have enough code already and we must improve the readability of some tests, reorganise dependencies, clean up namespaces and some other things we know are important. A tool like Sonar of something like that will provide us with metrics to measure the improvements over time. It's definitely the time to visualize code metrics
  • Dependencies diagrams are another type of metric that we should use now that. A quick overview of how the various namespaces are related to each other.
  • There are certain areas of the hexagon suffering from "primitive obsession" code smell. We want more objects within our business domain, and less primitives.
  • More information in commit's comments. Apart from the refactoring we apply or the name of the tests turning green or red, I'll try to explain shortly what is the benefit of every single commit. The reason to change the code. I've found myself searching for particular design decisions in the commits' history and realized that the information in the comments was not enough to find out what I wanted. Example: why I moved a method to a class, extracted a class... the "why" is not in the code so it's a good idea to add it in the form of comments in the version control system.
  • I want to learn how to work with Visual Studio without the mouse, because it's faster with the keyboard only. This is an old resolution that I want to approach now.
  • I realised that our style of "mob programming" is different to the original style proposed by Woody Zuill and his team. In the original proposal, the driver is mostly "keyboarding", focusing on typing what the navigators tell him to do. Our approach is different, we have the discussion and the person who clearly sees how to translate the idea into code jumps in the keyboard and expresses it in code, no one says to the driver what should be written. The driver leads the session when he is at the keyboard. It's sometimes easier to express an idea writing some code or pseudo-code, than trying to explain how the code is going to look like, and I think this has to do with the fact that talking constantly exhausts me. It also has to do with focus, the driver is the person who can implement the discussed idea faster, who knows the code better. Whenever the driver is stuck, the navigator who knows how to carry on, asks for the keyboard and becomes the driver. I find dictating awkward and sometimes irritating. So we are not following their rule: "for an idea go from your head into the computer it MUST go through someone else’s hands.". We try not to talk whilst the driver is typing just like in pair programming, because we want the driver to be able to listen what navigators have to say, and I can't type and listen at the same time. Perhaps we are not doing mob programming at all. But it works for us.
  • In order to keep the good energy and motivation in a mob or pair prog session, it's better to give up or take a break than working without feeling like it. I need to feel that my colleagues feel like working and thus I must feel like doing so too.
  • I really like the way Peter summarized the Hexagonal Architecture, focusing on the direction of the dependencies. A simple diagram with two boxes joined by an arrow pointing from one to the other, was enough for people to understand it. Also the onion was a good idea.

Regarding the Global Day of Code Retreat, there are a bunch of things I learned from Peter and from the day itself:

  • If there are no sponsors buying food, I want to buy food myself for me and for all the participants. This year I brought the food in the afternoon but I should have brought it in the morning, when people were hungry. Next time I'll arrive in the morning with breakfast for everyone. I missed the relaxing moment of the morning break sharing some fruit and coffee or tea.
  • Whenever I talk very serious aiming to remark something important, I look like I am rude. I don't realize that until I see people's faces and by then I feel bad about it. To avoid this situation I'll think twice before sending the message. I must be quiet, talk more slowly, think from a positive angle and use positive words. Words like "no" or "not" or "don't" may be negative. I want to read about Non Violent Communication and practice it.
    As an example, during the retreat in one iteration's retrospective I said that the facilitators (Peter and me) were not there to teach. My aim was to encourage people to learn from themselves rather than expecting some kind of master class or demo from our side, but the way I said it was understood as ... "I am not here to help you, or I don't care about you" as some people told me afterwards. It had a negative impact in some people's motivation.
  • At the end of the day, after the final retrospective, in the pursuit of feedback and appreciation I talked in such an unfortunate way that made people feel in debt with us. But again I didn't realise until I saw people's reaction. My aim was to discover what benefits did participants find out during the day, what did they take away so that next time I could maximize it with specific actions or exercises.
    When it's obvious that I've dedicated time and energy working for others, I must be very careful not to express that explicitly because it will make people feel in debt which is not what I wanted.

Several friends have spoken to me about Non Violent Communication (NVC) in the last 5 years or so, I believe Diego Rojas was the first one, working with Peter was a trigger point for me to really start digging into the subject. Thank you for the recommendation Peter and for this excellent video by Marshall Rosenberg, the father of NVC:

C#, Java and other languages have the same behaviour when it comes to reference types.

  1. public class SomeClass {
  2. public string someField;
  3. }
  4.  
  5. var instance1 = new SomeClass(); // instance1 is a reference to an object in memory
  6. var instance2 = instance1; // instance2 is a copy of the reference
  7. instance2.someField = "changed";
  8. instance1.someField == instace2.someField // -> true
  9. instace2 = new SomeClass();
  10. instance2.someField = "changed again";
  11. instance1.someField != instance2.someField // -> true -> they are different objects
  12. instance1.someField; // -> "changed" -> nothing changed
  13.  

The dot symbol after the variable name (instance1 or instance2) accesses the actual
object referenced by that variable. So before the dot, we have a variable referencing an object, and
after the dot we have the actual object.

  1. instance1.someField;

Means: get reference instace1, then access the object, then access someField

Passing objects to functions has exactly the same behaviour, function parameters behave like variables assigned to the original arguments.

  1. public static void SomeMethod(SomeClass arg1){
  2. arg1.someField = "changed";
  3. }
  4.  
  5. var instance1 = new SomeClass();
  6. SomeMethod(instance1);
  7. instance1.someField; // -> "changed" -> field has changed
  8.  
  9. public static void OtherMethod(SomeClass arg1){
  10. arg1 = new SomeClass();
  11. }
  12.  
  13. var instance1 = new SomeClass();
  14. instance1.someField = "changed";
  15. OtherMethod(instance1);
  16. instance1.someField; // -> "changed" -> nothing changed
  17.  

Instances of SomeClass are mutable because the value of someField may be changed.
This mutation may happen mistakenly as a result of an uncontrolled access to the object via some copy of its reference, causing unexpected side effects like defects and memory leaks.
As long as the application code can reach an object - has some reference to it - the garbage collector can't free the memory allocated for that object. Short version of our desktop app architecture as an example:

  1. public static class EventBus{
  2. private static ISet<Subscriber> subscribers = new HashSet<Subscribers>();
  3. public void AddSubscriber(Subscriber subscriber){
  4. subscribers.Add(subscriber);
  5. }
  6. ...
  7. }
  8.  
  9. public class View{
  10. public ViewModel ViewModel;
  11.  
  12. public View(ViewModel viewModel){
  13. ViewModel = viewModel;
  14. }
  15. public void Init(){
  16. EventBus.AddSubscriber(ViewModel);
  17. }
  18. }
  19.  

The life cycle of the View instance is controlled by the framework, not by us. It may create a new instance every time the view is shown on screen and destroy the instance as it disappears. However we are adding a reference
to the static list of subscribers in the EventBus. As long as the subscribers list is not flushed, the garbage collector won't be able to set memory free for ViewModel and View instances, even though the view may not be even displayed. Opening that view many times will increase the memory consumption every time, that is a memory leak. In this particular case we unsubscribe the instance from the bus before hiding the view:

  1. public class View{
  2. public ViewModel ViewModel;
  3.  
  4. public View(ViewModel viewModel){
  5. ViewModel = viewModel;
  6. }
  7. public void Init(){
  8. EventBus.AddSubscriber(ViewModel);
  9. }
  10. public void Clear(){
  11. EventBus.RemoveSubscriber(ViewModel);
  12. }
  13. }
  14.  

In the case of the bus there isn't much we can do to avoid having two references to the same object in two different places, we have to be aware of this behavior. In C# there is the concept of Weak Reference but as far as I know we can't use it on WinRT (tablets).

In some other cases though we may avoid side effects:

  • Avoid more than one reference per object, avoid state
  • Keep variables local, avoid instance variables (fields)
  • When the object is a value object, design it to be immutable
  • In the case of collections, use ReadOnlyCollection when they must keep their size
  • If the object can't be designed immutable but you need to avoid state changes at all cost, clone the object returning a deep copy of it

We may be tempted to clone objects every time someone asks for a reference to them. However this may not be possible (like with the EventBus) or it may be too expensive and complex. I'd say that cloning is the last alternative and perhaps the need for it is a design smell. Who is responsible for ensuring that object references are not causing memory leaks? It boils down to the "less surprise" principle. We should design interfaces (methods) in such a way that it's obvious how references and state are going to be managed. If it looks like the consumer (the one asking for the reference) will not be aware of it and the consumer will likely make undesired changes to the object, then cloning the object could be a good defensive approach. But I would rather try to think how to make the API more expressive considering context and level of abstraction. I assume that the caller understands how references work.

If you, dear reader, provide some code examples I will be able to clarify my point with code. I'll update this post if I come up with some snippets.

In order to learn from others I must trust them and open my mind enough to see them as potential teachers even if  they are - apparently - less experienced than me in certain knowledge area. The lessons to be learned may not necessarily come from the things others say or do but from the synergy that comes out a trustworthy relationship. It could be something I say myself as an answer to an unexpected question, one that makes me reflect from a different angle. If I believe I can't learn from other person then I am actually building a mental barrier that will prevent me from learning anything at all. No matter if I think the other person's idea is wrong, my attitude should be open enough to let him do and show me how he works in a way that he feels encouraged to do so, in a safe and collaborative atmosphere. In the case am completely sure that the idea (approach or technique) is not appropriate because I've tried it before and failed (even many times), I may suggest not to go there but still give the others the chance to fail themselves: "Do you really think that is the best way to go?, I don't think it is but if you definitely want to try let's do it". Using questions rather than imperative sentences may instill the right amount of uncertainty in others so that they may also be open minded and discuss better ways.

To build a trustworthy relationship one must learn to listen to others. Be willing to listen to others is the first step. Everyone deserves attention, everyone has stories that are worth listening, and so I do. By letting others express themselves I am giving myself the same margin of trust and tolerance that will make me feel comfortable, creative and valuable when talking to others.

Valuable information is not only in what people say but more importantly, in how they say it. When someone criticizes a third person who is not present during our conversation, that's an opportunity for me to know my speaker better. That third person is pretty much irrelevant in the conversation, the important information comes in the way the speaker expresses her feelings, which let me know about her current mental state and the trigger points that make her upset, annoyed or whatever the feelings are. It's a chance to understand my speaker better and be empathetic. Also the fact that she is verbalizing her thoughts may help her listen to herself and realize that she went too far, this is, verbalizing thoughts may break the negative loop. At least it happens to me, when words are already off my mouth there is no way I can hide, the commitment is done and I end up on a different path often feeling sorry about it.

Some people need silent moments, even "uncomfortably" long ones, in order to start talking. I have to discover what are the conditions under which he will feel safe enough to bring what he knows or whatever he's to say.

Listening to people with full attention requires quite a lot of energy. It's important that I tell them when I am running out of energy so that I can make a break. A few minutes of break per hour make a big difference. Recognizing the right time to leave the conversation for tomorrow is also crucial.

XP Team Building

Let the team walk its path

Every team walks at its own pace and I haven't found a way to speed it up myself, I don't think there is one regardless of whether you are an external coach or a regular member of the team. Trying to push the team will screw up the work environment, the pressure may introduce interpersonal conflicts and severe damages in the quality of the product. I mean, people will do stuff they do know it's wrong because of the sense of emergency. On the other hand trying to pull the team away will give its members the impression that they are not trusted professionals, again causing problems among people and discouraging them from being proactive and willing to learn.
The only way we can help the team progress is to help them walk their own path, removing impediments along the way, answering questions when asked to do so.

I've learned that it's not possible to develop a software product at the speed that I'd like whilst mentoring people. I have to choose either to be a trainer or to be a developer but not both things at the same time because the goals are different. When working as a trainer the goal is that people learn effectively and the best way, for us humans, to learn is by making mistakes that let us learn from ourselves. As a mentor I must combine small theoretical explanations, recommendations and practical examples with time for people to practice and to make their own decisions. They must have the chance to fail and discover. If they don't recognize the failure my mission is to provide feedback and explain why is this or that a mistake and what are the consequences. Deep lessons are learned with pain - success is fantastic but it doesn't teach. However this style of mentoring takes a lot of time, it's probably the top most time consuming way. It's a company wide commitment, an effort for everyone.

Often companies ask us to join them for a new project that must deliver value within a tight schedule and at the same time they want to build up a team of XP developers with people that have never been exposed to XP. I must say this is completely impossible in my experience. If the quality of the product needs to be excellent and deadlines are tight, the best thing the company can do is to hire a seasoned high-performing XP team whose members have been working together for years. On the other hand, if the actual goal is to build up a team, this is an investment that lasts several years. According to my experience, a group of 6 to 8 developers become an XP team after 2 years of training, guidance, reviews and practice. It requires several training courses during the various stages of the transition, practical examples, guidance and moreover it requires small failures (hopefully reversible ones). People have to have the margin to fail and learn from their mistakes. During this period some people will very likely leave the company and some new people will join.

I know the word quality is too abstract, we don't have a definition for what quality is but I am actually talking about well-known maintenance issues. A common mistake beginners make is to write brittle and hard to maintain tests that with time impede developers changing or adding features. Those tests are eventually deleted. It's waste unless you consider this to be another stage in the team's learning curve.
Nobody writes perfect code anyway, every team makes mistakes so the point is not to aim for perfection. The point is to avoid or minimize the amount of things we do know are waste, basically because we have failed in the past.
Hiring seasoned external consultants means they won't make the same mistakes they did in the past although they'll make new mistakes. Every team is different as well as every project.
As a consultant I won't prevent the team from making mistakes when the goal is to train them, instead I'll try to keep the cycles small enough so that mistakes can be fixed soon and cheap. But it's up to the team to ask for feedback and review, my job is not to control the source code - it's to support the team!

In some situations it could be beneficial that a small group of experts write the "walking skeleton" with the first group of product features in order to define architecture, style and conventions that others can follow. It serves to explore risks and exposes an example that others can follow. There are several perils of this approach though. I'd be careful with it - sorry don't feel like writing about these drawbacks now.

EventBus in a Windows 8 app

eventBusWinAppHow to communicate different pages of a Windows 8 App? How to manage the life cycle of the pages?

Pages are instantiated by the framework when asked to navigate:

*.xaml.cs:

  1. frame.Navigate(typeof(MyPage));

It will be a new instance of MyPage everytime unless the pages are cached. To set up the page cache, add this line to the beginning of

MyPage.xaml:

  1. <Page
  2. x:Name="pageRoot"
  3. x:Class="MyNamespace.MyPage"
  4. NavigationCacheMode="Enabled"
  5. ...
  6.  

 
Cache can be clear as described here as long as the NavigationCacheMode is "Enabled" and not "Required". The "Required" pages can't be deleted from the cache as explained by Andreas Hammar.

The page's life cycle is controlled by the framework although we can configure the cache, therefore my objects - those whose life cycle is controlled by myself - should not reference pages in order to avoid memory leaks and undesired side effects.

We've decided that Pages and other UserControls are the ones which create and manage ViewModel's life cycle (we're using MVVM pattern). The page's codebehind (MyPage.xaml.cs) contains a reference to ViewModel.cs which is a plain old C# object that contains the GUI logic. MyPage instantiates the ViewModel in its constructor. So there should be no references to ViewModels from other objects.

MyPage.xaml.cs

  1. public MyPage(){
  2. InitializeCompontent();
  3. ViewModel = new ViewModel();
  4. DataContext = ViewModel;
  5. }

However I can't avoid references to the ViewModel from the EventBus (simple pubsub static class) because it's the mechanism we are using to communicate different parts of the application:

ViewModel.cs:

  1. public void SubscribeToEventBus(){
  2. EventBus.Subscribe(this); // static method
  3. }
  4. public void UnsubscribeEventBus(){
  5. EventBus.Unsubscribe(this); // static method
  6. }

To work around this problem, I make sure the ViewModel contains references to the bus only when it's active (visible on screen):

MyPage.xaml.cs:

  1. public override void OnNavigatedTo(){
  2. ViewModel.SubscribeToEventBus();
  3. ViewModel.Initialize(); // optional
  4. }
  5. public override void OnNavigatedFrom(){
  6. ViewModel.UnsubscribeEventBus();
  7. }

When the ViewModel requires some data previously generated in another view and stored in the AppState, it raises an event through the bus saying it's loaded and then the AppState listener replies back through the bus sending the required data.

We haven't found a built-in way to reset the application clearing all data so we've implemented a reset method. The reset is an event triggered by a button in the bottom bar, sent through the bus. Our App.xaml.cs object which is the singleton that starts the application handles the event clearing all data. The sequence is important to avoid memory leaks

App.xaml.cs:

  1. public void Handle(AppReset appResetArgs){
  2. EventBus.Clear();
  3. AppState.Reset();
  4. InitializeServices();
  5. EventBus.Subscribe(this);
  6. ResetXamlCache(); // this must be the last thing to clear
  7. NavigateToRootPage();
  8. }

Only the App object subscribes to the AppReset event. Other global events like a connection failure are also handled by the App object.

A final reflection is,... Why do we need an EventBus at all? We could just inject the same AppState instance in every ViewModel to share data among the different screens. Something like a NavigationService could have solved this for us. The following pseudocode illustrates the idea:

NavigationService.cs:

  1. public static void NavigateTo<T>(){
  2. var frame = (Frame) Window.Current.Content;
  3. var viewModel = Factory.ViewModelFor<T>();
  4. frame.Navigate(typeof (T), viewModel);
  5. }

MyPage.xaml.cs

  1. protected override void OnNavigatedTo(NavigationEventArgs e){
  2. ViewModel = e.Parameter as ViewModel;
  3. }

Then in the Factory we could inject the same AppState to all ViewModels and manage their life cycle. This indirection level could have changed out architecture. A custom base paged could implement the "OnNavigatedTo" to avoid duplication.

Thanks to my friend Juan M. Gomez for the idea of the navigation service.