Learn To Craft at Microsoft

ApprenticeshipA few weeks ago I was able to attend an event hosted by Microsoft France about the software craftsmanship movement named “Learn to craft“. This presentation was made by Jean-Laurent Morlhon, Bruno Boucard and Thomas Pierrain.

Even if I already read a lot about the topic (I went to some meetups about software craftsmanship and I went to a conference), I was glad to have the opportunity to go to this event, you never know what you might learn.

Presentation

At the beginning there was a presentation of the software craftsmanship movement, its origin, its values, its goals. I will not go into the details, you can learn more here. I was just surprised that there was no mention of the manifesto, not that I believe that it should be signed, I let you decide whether you want to sign it or not.

What I like about the manifesto however is the fact that it shows a close relationship with the manifesto for agile software development, which in my opinion is an important aspect: Software Craftsmanship is part of the agility movement, with a big focus on technical aspects.

swcraft

TDD & Pair Programming

After this presentation Bruno and Thomas put their hands on the keyboard in order to show us a pair programming session while doing Test Driven Development (TDD). This exercise aimed to show us how to go through each step of the Red-Green-Refactor loop of TDD but also how to collaborate as a pair.

In a pair communication is key, both developers have to think about the problem they are trying to solve and they exchange a lot. Now the question you might have is how to equally share the keyboard in a pair programming session, well the TDD approach is helpful to solve this case.

What you can do is: one of the two developer starts by writing a failing test (red), make it pass (green), refactor the code if necessary (refactor), write a new failing test (red) and give the keyboard to his partner. This developer now has to make the test pass (green), do the refactoring and write a new failing test (red), at the point the first developer take the keyboard back to continue the implementation. And repeat this pattern every iteration (or two) to share the keyboard as much as possible.

By doing pair programming you will be able to share your technic, tips and tricks with the members of your team. It is a great way to learn new shortcuts as well, I personally learn a lot of them this way.

swcraft-pair

Refactoring legacy code

The next session was presented by Thomas and was about refactoring, in the example Thomas used the Gilded Rose refactoring kata. The goal of this kata is to simulate the need to add a new feature in an existing code base, a not so great code base with a lot of duplication.

If you are lucky there is already some tests covering the code, if not you will have to make sure that you won’t break anything while adding new code. In the session Thomas used an interesting method to make sure he won’t break the existing features: he duplicated the code to be able to refactor it without losing it. Then he gave the same inputs to the two parts and checked that the outputs were the same.

For the refactoring itself he used a “counter-intuitive” strategy: copy-pasting! The Gilde Rose code is full of if-else statement and a lot of them are redundant but it is not obvious at the first glance. Therefore the technic is to make them even more redundant to detect the parts in the code that can be refactored into methods to clean the whole code base. You make the code even worse that it already is to ease the refactoring. The concept is difficult to explain with a few sentences, seeing it in practice however is definitely counter-intuitive yet the result was very efficient, I was impressed by this strategy.

swcraft-legacy

Testing untestable code

In the previous session the code was not under test but it was testable, but we know that it is not always the case. Some code bases are tightly coupled with a database or a web service for instance, if you want to test the code you need a working database and/or a working web service.

Bruno also used a kata (from Sandro Mancuso) to demonstrate a way to get rid of these “hard” dependencies in order to test the rest of the code. The kata simulates a system using classes that cannot be used in a test context.

In this exercise the goal is to detect these dependencies and extract them so you can inject them using dependency injection and therefore you can mock them in your tests. This strategy can be frightening because in order to write tests, you first need to refactor the code and in the previous session we saw that tests give you a safety net when refactoring some code. But it this case, there is no choice, you have to do the refactoring without them so you need to be very careful and if something goes wrong you can always rollback the changes even if nobody like this “final” solution.

swcraft-untestable

Some personal thoughts

This event was definitely made as an introduction to software craftsmanship for people who have (almost) not experienced it, with a big focus on practices and not just theory. There is a lot of content I already knew, which is a good news for me I guess. But I also learned new tricks and technic allowing me to remind me that I still have a lot to learn, and that’s great!

I was also very surprised to see that about half of the attendees were not .NET developers, there was a lot of Java people (at Microsoft’s!). And this show us that the software craftsmanship movement is not technology based, it addresses everyone no matter where you come from, it is an ideal with values, a community!

I want to thank Microsoft for hosting the event, and of course I am grateful toward Jean-Laurent, Bruno and Thomas for taking the time to animate this event and spreading the values of the software craftsmanship. If you want to learn more you can visit their site learn.tocraft.fr (in french).

See you next time!

swcraft-resources

 

Primitive type obsession

the-old-vs-the-newAs professional developers, we are asked to automate behaviors by writing high quality code. Our favorite programming languages allow us to do so by providing some primitive types we can manipulate in our program. Yet he can be easy to fall into the trap of primitive type obsession. This code smell occurred when we use primitive data types (string, int, bool, …) to model our domain ideas.

The problem

In one of my previous blog post, I demonstrate how to create custom model validation using ASP .NET MVC using an IP address as an example. I had the following property in my Model:

public string IPAddress { get; set; }

This is clearly a primitive type obsession, because using a string to store an IP address can be dangerous, the compiler will not prevent me from writing the following code:

model.IPAddress = null;
model.IPAddress = "";
model.IPAddress = "foobar";

In C# .NET a string can contain much more information than an IP address, the later is far more specific and should be designed accordingly. I will then use Object Oriented Programming and encapsulation to create a custom IPAddress type.

The refactoring

In the other article I explained that the address follows the IPv4 format which is composed of 4 bytes, then let’s create a class representing this concept.

public class IPAddress
{
    public byte FirstByte { get; set; }
    public byte SecondByte { get; set; }
    public byte ThirdByte { get; set; }
    public byte FourthByte { get; set; }
}

Does it make sense to be able to instantiate an IPAddress object without setting the bytes? Not really but for now it is possible, let’s fix that!

public class IPAddress
{
    public byte FirstByte { get; private set; }
    public byte SecondByte { get; private set; }
    public byte ThirdByte { get; private set; }
    public byte FourthByte { get; private set; }
 
    public IPAddress(byte first, byte second, byte third, byte fourth)
    {
        FirstByte = first;
        SecondByte = second;
        ThirdByte = third;
        FourthByte = fourth;
    }
}

I now have an object that actually represents an IP address that must be instantiated with all the data it requires. And I now have a class where I can add related logic to ease its use.

public class IPAddress
{
    public byte FirstByte { get; private set; }
    public byte SecondByte { get; private set; }
    public byte ThirdByte { get; private set; }
    public byte FourthByte { get; private set; }
 
    public IPAddress(byte first, byte second, byte third, byte fourth)
    {
        FirstByte = first;
        SecondByte = second;
        ThirdByte = third;
        FourthByte = fourth;
    }
 
    public static bool TryParse(string ipAddress, out IPAddress ipaddress)
    {
        // some validation logic & parsing logic
        // ...
    }
 
    public override string ToString()
    {
        return string.Format("{0}.{1}.{2}.{3}", FirstByte, SecondByte, ThirdByte, FourthByte);
    }
}

I switched from primitive type obsession to “domain modeling” by creating a value object. This kind of refactoring is very helpful for a lot of other cases. For example country codes stored in string while they are only 2 or 3 characters long with only a pre-defined number of possible values. Or an amount represented by an integer which can be negative and completely leaves out the currency of this amount. These are only a few examples among many.

It’s easy to fall into the trap of this code smell, using primitive data types is quick but it can allow unwanted side effects you will have to check whereas value objects protect the code from such behaviors.

See you next time!


Image credits:

http://erikapov.blogspot.fr/2010/01/old-vs-new.html

Are you a software Boy Scout ?

boy-scout

If you are a developer like me, you probably worked on a legacy code based application. If not, don’t worry (or do) it will certainly happen… We all know a project that we fear to open because it is just a huge mess without a single test and nobody really understand how it works, it just does. Every software team has to work in order to prevent the effects of technical debt.

Refactoring a whole application to make the code “cleaner” can take an enormous amount of time, it can be weeks or sometimes months, depending on the project size and complexity. Some organization will incorporate refactoring phases during the development life-cycle. But since during these periods, the team does not provide any new features (i.e. no value), having these refactoring phases is a hard sell. Time to become a Boy Scout then !

What the boys scouts have to do with software development ? The answer is found in their rule :

“Always leave the campground cleaner than you found it.”

This simple rule can be applied to code and especially legacy code, and it becomes :

“Leave the code better than you found it.”

I present you the Boy Scout Rule (BSR) of programming. Making the code “cleaner” can be done at any moment, and it can be done piece by piece, no need to wait for a “Big Bang Refactoring” phase.

If you have a legacy project it is likely that you will have some improvements or bug fixing to do in it. This is the perfect time to embrace the boy scout philosophy. Of course after your passage the application will still be legacy but a bit less, and the next time you will improve it again. The code will become better with time and one day you’ll stop considering the project as a legacy one.

For example it is possible to rename a variable with a more meaningful name. Given the following code to calculate a triangle area :

var res = b / 2 * h

After the BSR applied :

var triangleArea = base / 2 * height

This is not much but it will help the next developer (maybe you) to understand the code and its purpose. And next time you will see that this piece of code is duplicate in several parts of the code. Time to create a method then :

public int CalculateTriangleArea(int base, int height)
{
    return base / 2 * height;
}

You now have a method that can replace your duplicate code and that can be easily tested with your favorite automated testing framework ! I know that this example is really simple but I’m sure you’ll find these kinds of easy “cleaning” in your applications.

There is a type of code refactoring I often use to make my code more understandable and to ease maintainability : moving repeated magic number value into a single constant variable. For example, a few years back, the french VAT was equal to 19.6% and now it is 20%. I let you imagine the pain it could have been to change every “19.6” in some projects where it could have been far easier to use a single constant with a meaningful name.

There are a lot of refactoring techniques to improve your code base, Martin Fowler gives you a list of some of them here.

A software craftsman does not fear legacy code, by following the Boy Scout Rule he will improve his projects.

See you next time !