Blog

Te ayudo a presentar

Vienes al AOS2016? Vamos a coincidir quizás en otro open space? Si nunca has presentado una sesión pero tienes algo que te gustaría compartir con la comunidad y te cuesta un poco arrancar y dar el paso, yo me ofrezco a echarte una mano. Te puedo ayudar a preparar el discursito de presentación de la sesión para que la gente entienda bien la temática y el formato y obtenga votos. Podemos salir juntos a contar la idea. Luego tambien podemos facilitar la sesión juntos (siempre y cuando salga votada), pero necesitaríamos prepararla un poquito antes del evento sobre todo si es un tema que yo desconozco. Sería una especie de "coaching" para facilitar o ser ponente en una sesión. Lo que haría es darte feedback sobre el material y el enfoque, en base a mi experiencia.
He dado muchas charlas y facilitado bastantes sesiones ya en open spaces y en otros formatos de evento. Mi experiencia puede ayudarte a ganar confianza y sentir que no estas sola, o solo. No hay ningún peligro, es un entorno controlado.

Esta idea la he copiado de Lisa Crispin que en su iniciativa de fomentar que haya más mujeres en el sector TIC, invita a ponentes femeninas que nunca han presentado en una conferencia, a presentar con ella.

Simplemente mándame un email, un tweet o un DM y buscamos la forma de preparar de la sesión.

Nos vemos en Santiago!

Así fue mi paso por Fon

Hace unos meses tuve la suerte de ser contratado por Fon para impartir un curso de TDD a uno de sus equipos de desarrollo en Madrid. Una oficina chulísima y un equipo entregado que prestó atención máxima desdel el minuto 1.

IMG_20151202_112556

Fon es una empresa de la que he oído hablar practicamente desde sus orígenes porque sonaba mucho en el mundillo geek desde siempre. Tenían fama de hacer las cosas bien. Así que tenía ganas de visitarles y ver qué se contaban hoy en día donde el Wifi ya no parece tan importante. Sin embargo me contaron que lo están petando con el roaming wifi en varios países.

Lo único que me faltó para que hubiese salido todo del 10 es conocer a Daniel Brandi que justamente esa semana estaba en un evento en Londres y no nos pudimos ver. Me sorprendió gratamente que muchos de los participantes en el curso ya me conocían y se habían preparado preguntas para sacarle el máximo partido a esos dos intensos días de formación.

IMG_20151202_112633

Agradezco especialmente a Joan Fisbein la atención, el apoyo prestado y las agradables conversaciones durante la comida.

Parece que el curso cambió la forma en que el equipo ve los tests, tanto en calidad como en cantidad. La gente se dió cuenta que la cobertura no es un objetivo en sí mismo sino que lo importante es crear unos tests mantenibles que mantengan un buen compromiso entre seguridad y mantenibilidad.
Las conversaciones fueron muy interesantes y la gente muy maja.

Además en este curso pudo venir conmigo nuestro aprendiz Miguel A. Viera y facilitar alguno de los ejercicios en el segundo día. Miguel se quedó alucinado con la oficina.

IMG_20151201_121617

Ahora mismo Fon está buscando desarrolladores Java senior. Es un buen momento para enviarles un CV si estas buscando nuevos retos.

Así viví el rodaje de NMNL Episodio 2

Ni Monos Ni Lagartos, Episodio 2:

No tenía ni idea de qué era esto de "Ni monos ni lagartos" NMNL, (más allá de la pegatina de Autentia del mono con el lagarto en la cabeza con atajos de teclado de Vim) porque cuando Isabel Rodriguez me llamó para decirme que habían pensado en mí para el segundo episodio, el primero todavía no se había emitido. Así que pense... bueno serán un par de preguntillas rápidas al estilo de otras entrevistas cortas que he hecho con Autentia. Pero después me dijo que vendrían a buscarme al aeropuerto con las cámaras y a rodar en el coche y en lo alto de no se qué puente de Madrid y pensé se les ha ido la pelota..., qué molón! me apunto!
Creo que el hecho de que pensaran en mi como protagonista de un episodio de NMNL fue que iba a impartir un taller de Refactoring en Autentia. Es lo bueno que tiene recordarle a la gente que estas ahi, que pueden contar contigo.

NMNL es algo así como "el Salvados" del mundo IT 🙂 un programa donde entrevistan a personas que ellos creen que son relevantes dentro del sector.

En este viaje me acompañaba mi hermana Raquel de tan sólo 18 años en su primera visita a Madrid y le sorprendió mucho la noticia del video, no sabía ni qué ropa ponerse. Hubo algunas preguntas sobre ella durante el rodaje pero luego quedaron fuera de los videos porque la verdad es que tres días rodando juntos no caben en los videos!
El primer día rodamos en el aeropuerto, en el coche y en la oficina de Autentia. Desde el principio me sentí super cómodo con la cálida acogida y la profesionalidad del super equipo de Autentia Media: Isabel, Alba, Leti y Sonia. Nos trataron de maravilla tanto a mí como a Raquel.
Si alguna vez tienes la suerte de que te propongan protagonizar un episodio de NMNL, no lo dudes, es una experiencia única. No importan los nervios porque no es un directo, las tomas se repiten las veces que haga falta y luego en la edición muchas cosas se dejan fuera. El equipo de Autentia se lo curra para que parezcas un gran orador, cortando pedacitos por aquí y por allá.

El segundo día rodamos en La Gatoteca, un fabuloso refugio felino en el centro de Madrid. Fue la parte de preguntas personales donde pude responder a muchas de las preguntas típicas que la gente me hace cuando vamos a comer juntos, por ejemplo preguntas sobre el veganismo o sobre nuestro pequeño refugio felino. Estuve tan agusto rodeado de gatos y tan inspirado gracias a la ayuda de Alba y del resto del equipo que grabamos mucho más de lo que cabe en un episodio de 20 minutos, que es aproximádamente lo que dura el programa. Así que en la producción han tenido el detallazo de sacar otro video, con la entrevista personal entera:

La parte más personal de la entrevista

Agradezco especialmente a La Gatoteca el gran gesto que tuvieron con nosotros al reservarnos la planta baja practicamente durante toda la mañana. Confiaron totalmente en nosotros y nos facilitaron la grabación además de ser amables y explicarnos de primera mano como funciona. Si estas en Madrid y piensas en adoptar un gatito, no dejes de visitar La Gatoteca (y si es una pareja mejor, así se dan compañía! los gatos mejor adoptarlos en pares). Es un sitio estupendo incluso para comprobar si sigues teniendo aquella alergia que te había disuadido de acoger animales!

Ese día como de costumbre tenía varias reuniones en distintos puntos de la ciudad y además la conferencia JSDay que empezaba por la tarde. En la Gatoteca estuvimos durante la mañana. Por la tarde rodamos por fuera de Campus Madrid en una plazoleta, la parte profesional de la entrevista. Mientras yo mantuve una reunión de negocio, Raquel pudo quedarse con las chicas a comer y así aprender un montón de cosas sobre cómo trabajan, cosa que a su edad es una información muy valiosa. De hecho ibamos buscando que en este viaje conociera diferentes profesionales para ir haciendose una idea de posibles oficios a aprender.

En esta entrevista hubo un pedacito donde pude hablar de nuestra experiencia en DAG (Domingo Alonso Group), el cliente que nos ha ayudado en gran medida a convertirnos en Codesai. Para una convención interna de DAG, Autentia tuvo el detalle de producir otro vídeo más, que contenía exactamente esta parte:

Hablando de DAG (Domingo Alonso Group):

Un buen pedazo de la tarde se nos fue rodando, por lo que llegué tarde al JSDay, cosa que espero que me perdonen los organizadores. Haré un post sobre el evento muy pronto, porque estuvo genial.

Se nos ocurrió la idea improvisada de que parte de mis compañeros de equipo participasen en NMNL pero como no hubo aviso con suficiente tiempo, la mayoría se había marchado de Madrid aprovechando el puente. Modesto fue el único que pudo venir a grabar a Campus Madrid pese a que era el cumple de su hija y que estaba muy cansado tras una semana intensa. Si lo hubíese sabido con antelación quizás podriamos haber estado 5 personas del equipo, pero no me lo imaginaba. Este fue el motivo de que me saliese de la sala en medio de algunas confernecias del JSDay.

El montaje final de NMNL Episodio 2, me ha parecido un montaje y una producción de una calidad enorme.

Todo el feedback sobre las entrevistas es bievenido.

Mando un fuerte abrazo a todo el equipo de Autentia por su apoyo y dedicación, sin la cual nada de esto sería posible.

El feedback que he recibido de personas cercanas es que se hace corto, que pasa muy rápido. Esta es una gran señal.

Event bubbling in C#

How to propagate an event from a low level class to a top level one:

  1.  
  2. public class TopLevel{
  3. public bool Bubbled { get; private set; }
  4. private MiddleLevel observable;
  5. public TopLevel(MiddleLevel observable){
  6. this.observable = observable;
  7. observable.Triggered += (s, e) => {
  8. Bubbled = true;
  9. };
  10. }
  11. }
  12. public class MiddleLevel{
  13. public event EventHandler Triggered;
  14. private BottomLevel observable;
  15. public MiddleLevel(BottomLevel observable){
  16. this.observable = observable;
  17. //One may be tempted to bubble like this:
  18. //observable.Triggered += Triggered;
  19. //However, Triggered is null unless there is already
  20. //a subscriber. This is a better approach:
  21.  
  22. observable.Triggered += (s, e) => {
  23. Triggered(s, e);
  24. };
  25. }
  26. }
  27. public class BottomLevel{
  28. public event EventHandler Triggered;
  29.  
  30. public void DoSomething(){
  31. Triggered(this, EventArgs.Empty);
  32. }
  33. }
  34.  
  35. [TestFixture]
  36. public class TestingEventBubbling {
  37. [Test]
  38. public void Bubbling(){
  39. var bottom = new BottomLevel();
  40. var middle = new MiddleLevel(bottom);
  41. var top = new TopLevel(middle);
  42.  
  43. bottom.DoSomething();
  44.  
  45. top.Bubbled.Should().BeTrue();
  46. }
  47. }
  48.  

Events can only be raised from within the declaring type. Unfortunately they can't be be passed in as arguments to methods. Only += and -= operators are allowed out of the declaring type. One way to stub out the event could be through inheritance:

  1.  
  2. public class BottomLevel{
  3. public virtual event EventHandler Triggered;
  4.  
  5. public void DoSomething(){
  6. Triggered(this, EventArgs.Empty);
  7. }
  8. }
  9.  
  10. public class StubbedBottomLevel : BottomLevel {
  11. public override event EventHandler Triggered;
  12.  
  13. public void RaiseEvent(){
  14. Triggered(this, EventArgs.Empty);
  15. }
  16. }
  17.  
  18. [TestFixture]
  19. public class TestingEventBubbling {
  20. [Test]
  21. public void BubblingWithStub(){
  22. var bottom = new StubbedBottomLevel();
  23. var middle = new MiddleLevel(bottom);
  24. var top = new TopLevel(middle);
  25.  
  26. bottom.RaiseEvent();
  27. //bottom.DoSomething(); will not throw the event!
  28.  
  29. top.Bubbled.Should().BeTrue();
  30. }
  31.  

But declaring the event as virtual and then overriding it, is very tricky: replacing the call to RaiseEvent to DoSomething, makes the test fail! Looks like events where not designed to be overridden. A better approach:

  1.  
  2. public class BottomLevel{
  3. public event EventHandler Triggered;
  4.  
  5. public virtual void DoSomething(){
  6. //SomeLogic would go here...
  7. Raise(EventArgs.Empty);
  8. }
  9. protected virtual void Raise(EventArgs args){
  10. Triggered(this, args);
  11. }
  12. }
  13.  
  14. public class StubbedBottomLevel : BottomLevel {
  15. public override void DoSomething(){
  16. Raise(EventArgs.Empty);
  17. }
  18. }
  19.  

Windows apps development best practices

I don't really know whether they are the best practices to be honest, and certainly there is a lot for me to learn but these are principles and practices that work well for us in the development of a complex native Windows App (Windows 8.1+) using C# and the MVVM pattern.

Files in my example (namespace + classname) :

  • Example.Views.App.xaml.cs            (Main app class)
  • Example.Views.Vehicle.xaml           (View)
  • Example.Views.Vehicle.xaml.cs       (View's Codebehind)
  • Example.ViewModels.Vehicle.cs     (View model)
  • Example.Domain.Vehicle.cs             (Domain model)
  • Example.ViewModels.AppState.cs   (In-memory app state)
  • Example.Views.NavigationService.cs (Our custom navigator)
  • Example.Views.NavigationParameters.cs (Bag of parameters to be sent to the target view)
  • Example.Domain.EventBus.cs         (Our custom
    pub-sub implementation, a singleton)

Page navigation is performed by the framework:

  1. ((Frame)Window.Current.Content).Navigate(
  2. typeof(Vehicle), vehicleId);

The first parameter is the type of the target Page and the second is an "object" intended to send any custom parameter. Such parameter is received as an argument of OnNavigatedTo method in the target page.
The code above is used to navigate from App.xaml.cs (Main page) to Vehicle (Page).

The NavigationService is an indirection level that sends the ViewModel to the View as the context object. It's used pretty much like Frame.Navigate:

  1. NavigationService.Navigate<Vehicle>(Window.Current, vehicleId);

Implementation (NavigationService.cs):

  1. public static void Navigate<T>(Window w, object context){
  2. ((Frame) w.Context).Navigate(typeof(T),
  3. new NavigationParameters{
  4. ViewModel = GetViewModel<T>(),
  5. Context = context ?? GetContext<T>()
  6. });
  7. }
  8.  
  9. private static object GetViewModel<T>(){
  10. if (typeof (T) == typeof(Vehicle)){
  11. return Factory.CreateVehicleViewModel();
  12. }
  13. ...
  14. throw new NotImplementedException("Can't navigate to such page");
  15. }
  16.  

This is how the view model is received in Vehicle's codebehind (Vehicle.xaml.cs):

  1. protected override async void OnNavigatedTo(NavigationEventArgs e){
  2. var navigationParams = e.Parameter as NavigationParameters;
  3. var vm = navigationParams.ViewModel as ViewModels.Vehicle;
  4. vm.SubscribeToEventBus(); // in case vm is a listener
  5. await vm.Initialize(); // in case of some initialization
  6. DataContext = vm; // set the DataContext at the very end
  7. }
  8.  
  9. protected override void OnNavigatedFrom(NavigationEventArgs e){
  10. if (ViewModel != null){
  11. ViewModel.UnsubscribeFromEventBus(); // release the reference
  12. }
  13. }
  14.  

Principles applied in the code snippet above:

  • DataContext is set in the last step of the method, not before. DataContext is set either in the codebehind or in xaml, but not in both places at the same time. If the DataContext is set in the xaml (DataContext="SomeProperty") and also in the codebehind, you can't guarantee which data will be finally set, race conditions could happen.
  • Pages and UI controls in general must not contain state. Avoid any field in the codebehind holding a reference to the view model. This is to prevent race conditions. We rather create a getter instead:
    1. protected ViewModels.Vehicle Vehicle {
    2. get { return DataContext as ViewModels.Vehicle }
    3. };
  • Avoid subscribing the codebehind to the EventBus, use the view model as the listener. Life cycle of the pages is controlled by the framework - this is specially important when caching pages via NavigationCacheMode="Required". Sending a reference to the EventBus will prevent the garbage collector from cleaning up the Page instance.

Avoid global statics: Although there is a single instance of AppState class - is a global singleton, we inject it into every view model that requires read or write access rather than having direct static references. The Factory knows the AppState singleton and injects it to the viewmodels. Although two different views may require the same data, we try not to store everything in the AppState but rather cache the service methods retrieving the required data and then injecting the same instance service to both viewmodels. The amount of data kept in the AppState should be minimal, basically it should contain identifiers that view models understand in order to pull data from the services. Sometimes it contains more data to avoid time consuming transformations or calculations, that's fine, it's a trade off.

Custom controls: We ended up having our own custom pages, inheriting the Page control to remove duplication from initialization process. One of such inheritors is generic: CachedPage, where T is the type of ViewModel. However in xaml you can't define a page inheriting from a generic class. To work around this minor issue we create an intermediate empty class:

  1. public class CachedVehiclePage : CachedPage<Vehicle>{}

Then in xaml we can set the type of our page to be CachedVehiclePage.

Nested user controls: When a Page contains a user control, the DataContext of that user control is the same than the Page's one. Neither the codebehind or the xaml of user control should overwrite the DataContext. The DataContext should not be set programmatically it's just inherited from the parent container. Otherwise there could be race conditions and memory leaks.

Data binding: We don't bind domain models directly to the GUI. The main reason is that double way binding requires public setters. Sometimes we create a bindable object that wraps the domain model exposing only ome properties. But we often create custom bindable objects from the domain model for the specific purposes of the view.

I'll update this post with more stuff that is working well for us.

 

 

A code review is not like watching a football match

In my experience a code review must have a goal. Some common goals are:

  • Telling others how you solved a common problem.
  • Warning others about certain perils (i.e race conditions, coupling...)
  • Asking concrete questions. Implementation or design questions.

When you expose some code to your colleagues in a meeting room, you should know exactly what you want to get from that activity. You want to learn, to tech or to warn others basically. Otherwise, if you just open up some code and ask your colleagues what's their opinion about the code, then everyone will say something. Exactly like watching a football match with friends, everyone has his/her opinion on how the coach should manage the team, how players should play... no matter how good the team play, there will be always someone opinionated bullshit. The code review will be frustrating and not very productive.

Remember to prepare a list of questions or tips to tell others, together with the code you want to share, before going to the code review.

I visited Scytl

In October 2015, just two months before the Spanish elections I was lucky to visit Scytl and work there as a consultant for a week. Thanks to my good friends Manu Martin (@ManuCervello) and Alvaro Garcia (@alvarobiz) who are currently working in there as agile coach and developer respectively. I met a different team each day of the week, it was quite challenging and interesting.

tdd-course.jpg-largeMore often than not, when I visit companies, I get to see a significant amount of coding horrors and technical debt. So I was curious about Scytl because I knew they were going to collect and count my vote together with other 30 million more two months later. They were the IT company designated to  collect and count the votes in the Spanish elections - among many other things like the website with the reports...
I must say that I really liked what I saw, they are brilliant security experts, very professional. Citizens' vote was absolutely private and secure. I was confident that my decision as voter was secure, that I could trust their software. It's a very good feeling... software one can trust finally!

And yes, two months later they did a fantastic job, and they even broke the voting count speed record. Congratulations!

One of the teams I worked with was exactly the one in charge of collecting the votes. They had really good architecture and design questions for me. It was a challenge. Their chosen solution was very smart, I liked its simplicity. There was a lot of pressure on this team and I explained how important it is to have some slack time in order to step back for a little while and rethink decisions. Too much pressure is harmful in my experience, the best ideas come up when the brain is relaxed.

I also worked with the team in charge of counting votes and I got to see the D'hondt algorithm, something totally new for a democracy illiterate like me. We had a very nice mob programming session with the whole team in the meeting room. People were skeptical about mob programming at first but they quickly grasped its benefits, it was a way to find out team conventions for example.

On the third or forth day I also spent the day with the mob, this time with another team. The focus was on refactoring and unit testing strategies apart from a code review. We had the chance to explore together some of the new features of Java 8 too. I emphasized the importance of learning the IDE's shortcuts and the automatic refactorings it provides - it was IntelliJ in this case. Nice to code with young people willing to learn and improve.

I emphasized the fact that communication among co-located teams is more effective face to face. Pairing for a while to integrate a new feature from the other team or some API change, feels nicer than sending emails back and forth. Dog fooding among teams could help improve collaboration given that some teams act as a kind of "customer" to others.

There was also a session with a group to discuss about values, principles, professionalism and motivation. An exchange of opinions and points of view. Unexpected and very enriching.

I didn't know that teams are multicultural with people from distinct nationalities. English is the official spoken language. Although my English is not too bad for a quick chat, I had some trouble understanding and communicating with some people from other cultures.  It reminded me of how tough it could be to work with people from other cultures, specially when English is not the native spoken language of none of us.

Scytl's people were excellent hosts, very welcoming and friendly. Thank you for a remarkable week!

Only one MessageDialog may be displayed

On Windows 8, a call to "await aMessageDialog.ShowAsync()" can only be made once, otherwise System.UnauthorizedAccessException will be thrown (E_ACCESSDENIED 80070005). This is a helper method to display dialogs although it's not thread-safe. It's inspired on StackOverflow answers:

  1. public static class DialogDisplayer {
  2. private static IAsyncOperation currentlyShownDialog;
  3.  
  4. public static async Task TryToShowDialog(MessageDialog messageDialog){
  5. try{
  6. RequestPreviousDialogCancelation();
  7. await WaitForUIThreadToBeReady();
  8. await ShowDialog(messageDialog);
  9. }
  10. catch (TimeoutException ex){
  11. //Logger.Information("Time out waiting for a MessageDialog to be closed");
  12. }
  13. catch (TaskCanceledException ex){
  14. CancelDialog();
  15. }
  16. catch (UnauthorizedAccessException ex){
  17. //Logger.Information("Multiple dialogs are being opened at the same time. There is a direct call to ShowAsync somewhere. Instead of using ShowAsync, use this method");
  18. }
  19. }
  20.  
  21. private static void CancelDialog(){
  22. currentlyShownDialog = null;
  23. }
  24.  
  25. private static void RequestPreviousDialogCancelation(){
  26. if (IsThereAnyOpenedDialog()){
  27. currentlyShownDialog.Cancel();
  28. }
  29. }
  30.  
  31. private static async Task ShowDialog(MessageDialog messageDialog){
  32. currentlyShownDialog = messageDialog.ShowAsync();
  33. await currentlyShownDialog;
  34. }
  35.  
  36. private static async Task WaitForUIThreadToBeReady(){
  37. var attempts = 0;
  38. while (IsThereAnyOpenedDialog()){
  39. await Task.Delay(TimeSpan.FromMilliseconds(100));
  40. attempts++;
  41. if (attempts > 5){
  42. throw new TimeoutException();
  43. }
  44. }
  45. }
  46.  
  47. private static bool IsThereAnyOpenedDialog(){
  48. return currentlyShownDialog != null && currentlyShownDialog.Status == AsyncStatus.Started;
  49. }
  50. }
  51.  

Usage:

  1. var messageDialog = new MessageDialog("Hello world");
  2. await DialogDisplayer.TryToShowDialog(messageDialog);
  3.  

Polymorphic test setup with template method

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.

Refactoring katas with your own codebase

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 😉