Extreme Programming: Test Driven Development

Red Green RefactorAs professional developers our role is to produce high quality software for our clients. To achieve this goal we must make sure that our application meets the requirements defined by the business analysts and works as expected, without side effects.

To achieve this, you should rely on a full automated tests suite. And to make sure that this tests collection is complete and cover all your code base you can practice Test Driven Development (TDD).

TDD relies on repeating a short development cycle where tests are writing before production code. This process can be defined by the 3 following rules.

  1. Don’t write any production code until you have written a failing unit test.
  2. Don’t write more of a unit test than is sufficient to fail or fail to compile.
  3. Don’t write any more production code than is sufficient to pass the failing test.

Thinking ahead

By following these rules you can implement the required needs step by step. And by writing the tests first you also have to think from a caller perspective, you are a client of your own code.

With this paradigm shift, you have to think of what is actually needed in order to complete the case you are working on and nothing more. It is helpful to avoid any unnecessary over-engineering phase that might happen in the early development phase. This way you can follow the YAGNI (You Aren’t Gonna Need It) and the KISS (Keep It Simple, Stupid) principles, you only code what you need, nothing more.

Immediate feedback

TDD makes you write your tests suite at the same time as your production code. This allows you to be able to refactor the code easily, and you will do refactoring all along the way.

Refactoring is even one of the 3 phases of TDD: Red, Green, Refactor. You start by writing a failing test (Red), you write code to make it pass (Green) and you refactor the code to make it cleaner (Refactor). And of course you make sure that the tests still passed after the refactoring before writing a new failing test.

By practicing TDD, you consistently work with a safety net, if something is broken you know it right away!

Leading to better design

The TDD approach forces you to write testable software, therefore it is likely that the code will be less coupled than if it was written straight away without tests first.

A less coupled application is easier to maintain and easier to extend with new behaviors. This way you can improve your code base by adding advanced programming patterns during refactoring phases when you actually need them.

Due to this fact, TDD is sometimes decomposed as Test Driven Design instead of Test Driven Development. Yet to achieve better design when using TDD it is important to know programming patterns and programming principles (e.g. SOLID in oriented object programming).

Living documentation

One of the benefit of having a full tests suite for your production code is that it can work as documentation for it. By browsing the tests of your APIs the caller knows how to use it, how to instantiate the classes and what the expected outputs are for the available methods.

And this kind of documentation is always up to date since it is bound to the associated code it tests, if the code is updated so are the tests otherwise it fails.

More about TDD to come

When writing these lines I am still new to TDD and to be honest I don’t practice it every time, especially when working on legacy project (which would not have become legacy if developed with TDD or proper code coverage at least…). But I strive to follow the TDD rules when adding new behaviors to an existing project covered with tests.

I really want to learn more about this practice and this is why I work on increasing my TDD skills with some side projects. I will share the experience gained from these projects in a near future on this blog.

At the moment I am convinced that using TDD is very helpful to produce high quality software in a concise way. It helps me thinking of the exact behavior I want/need for my program. I like the fact it gives instant feedback and allow constant refactoring without having the fear of breaking anything.

See you next time!

Extreme Programming: Pair Programming

pair-programmingAs professional programmers, our goal is to produce high quality software for our customers. Pair programming is a helpful technic that allow to reach this goal.

Developers do pair programming when they sit in front of the same computer to complete tasks for a new user story. To me it is a different job than pair debugging, where you work on existing code in order to fix it, in pair programming you create new functionalities for your application.

At first it can be seen as a waste of time since two team members work on the same machine and it might look that the capacity for these programmers is divided by two.

I do not share this opinion, to me pair programming is a very good way to improve efficiency when working on a new feature.

Staying focused

When you are two it is likely than there will be always one of the two developers that knows what should be done next. It is helpful when one in the pair starts to feel a bit tired, the other one can continue and you rotate regularly. This will prevent any loss of total focus during the development phase, but the pair should still do some breaks from time to time.

When one of the programmer is coding the other one looks at the written code and can detect mistakes early on, it is an effective live debugging technic.

Share knowledge

When a pair of programmers works on the same user story together they will share the knowledge of the implementation. They will both know how it has been developed, this way your team is no longer dependant on a single developer for knowledge of a specific feature.

Beside technical knowledge you can also gain a better understanding of the business knowledge related to the user story you are working on. For instance instead of having a developer working on the front office workflow (from a business perspective) and the other one on the back office one, both developers can pair-program on the two subjects to understand how the system should behave on the front side and on the back side.

The code is also written by several persons and therefore there is no code ownership, this will avoid situation like “do not touch my code!” or “I won’t touch code”. The code is owned by at least the two programmers forming the pair, a step toward egoless programming.

Share skills

Pair programming sessions are also good to learn new practices, tips and tricks. When working in pair you can simply discover a new shortcut for your favorite IDE you were not aware of.

And most of all pair programming can help you discover new skills and practice them. For example you can improve your Test Driven Development (TDD) technic when working with a pair that is more experienced than you are. During a pair-programming session, we (my teammate and I) developed an entire topic using TDD, one wrote a failing test and the other one had to make it pass and then write a failing test and so on. This was a very rewarding experience, we were both new to this yet we practiced together and improved our knowledge.

Pair-programming is a social activity, it takes time to learn and can be frustrated from time to time. Yet it is very helpful to share knowledge amongst your team, you can always learn something new from one of your peer.

This practice can seem like a waste of time but since the pair is always focused on the topic, it can go faster with a higher level of quality. You can find a study about costs and benefits of pair-programming here.

See you next time!

Extreme Programming: Acceptance Tests

Check ListIn the chapter about user stories, I explained that they should not contain every details for the feature. Yet the development team needs these details in order to provide value. The details are discussed between the whole team members and you write them down using acceptance tests.

An acceptance test represent a specific scenario for the given user story. They are written by the business analysts and the testers. The developers take no part in the writing since these tests are business focused and are not technical at all.

The acceptance tests are written during the development phase of the user story, this is mandatory since they must passed in order to validate the entire user story.

These tests must be kept and run each time a new build of the application is made. Because working on a new user story can have impacts on previous ones and you want to make sure that they are not broken. Therefore you should find a tool that allow you to run your whole acceptance tests suite automatically.

A common language

Earlier I said that the acceptance tests are written by non-technical people. This allow you to make them understandable by everyone, your whole team is able to read them.

To do so, you can use the gherkin language which has been created to answer this problematic. This language uses a Given-When-Then structure to define the steps of a scenario.

Let’s see an example with the following basic user story:

As a visitor, I want to login, in order to access the website.

I will now create two different acceptance tests with the gherkin syntax for this user story.

Given a visitor,
When I log in with an existing account,
Then I am able to access the website
Given a visitor,
When I log in with an undefined account,
Then I am not able to access the website

With these scenarios I get more details for the expected behavior of the application regarding the user story to develop. You can use acceptance tests to test incorrect behaviors.

One of the benefit of the gherkin language is that you can use it with several testing framework to automate your tests suite and then you can run them automatically. You can use Cucumber to do so, or Specflow with .NET, this will bring your acceptance tests to a whole new level.

Acceptance tests as proofs

Acceptance tests allow the team to prove that the user story is working as expected. You have a list of scenarios defining the behavior of the feature. And by using an automated tool, you can detect any regression quickly.

These tests are bound to the code written by the development team and therefore are up to date. If the code of the application is updated so are the tests or else it is likely they will no longer pass.

Acceptance tests as documentation

The other benefit I like about acceptance tests is the fact that they can provide documentation for the application. Every members of the team are able to read them to gain understanding of the expected behavior, very helpful for newcomers.

And since it is written by the business analysts, it uses the correct terms for the business domain. This should help the whole team to communicate by using the same vocabulary. It’s a step toward the use of an ubiquitous language for a Domain-driven design (DDD) approach.

Acceptance tests are complementary with the unit tests, they provide a good understanding of a feature and are readable by everyone. They bring the business analysts and the developers closer to each others by providing them a share ground. Using acceptance tests require a good collaboration in your whole team.

In my opinion having them is a big plus to avoid regression, like all automated tests they provide a good safety net for future developments.

See you next time!

Extreme Programming: Short Cycles

cyclesIn our world of digital technologies, things move fast and so do the needs of our customers. Thus, as professional software developers, we have to adapt our way of working on a project, being responsive to change is key.

For this kind of development environment, some project management models are no longer up to the task, like the Waterfall of the V-Model for example. To follow the Agile Software Development Manifesto, Extreme Programming (X.P.) is based on short development cycles.

By doing so, the development teams are able to produce new features for their products at a regular interval. The short cycles of X.P. are all about feedbacks, with them you can focus on the tasks/improvements that will provide the most value for your customers and for your company.

X.P. defines two “high-level” cycles for the development process, the iteration plan and the release plan.

The Iteration plan

An iteration is a period of time (1 to 3 weeks) during which the development team work on a set of user stories defined during an iteration planning.

The features to work on during an iteration are picked by the business analysts depending on the budget the team has. In this case the budget represent the amount of work the team can achieve for the given period.

When the next iteration is defined, the feature to produce should not change nor the priority of them. This way the developers can cut the user stories into different tasks and focus on them.

The Release plan

The user stories completed by the development teams have to be released in order to improve the products and to add value. This is defined during a release plan.

A release contains the work of several iterations, the user stories are chosen during the release planning and as the iteration planning the amount of work to achieve should not exceed the budget the teams have. The order of implementation of the user stories is defined for the release at this moment.

Once a release plan is defined the first iteration of it can be planned as well. The content of a release can change, some user stories might be cancelled, others might be introduced or the priority for some might change. Yet this should not have impact on the current iteration.

Extreme Programming like others “agile” methodologies is focused on delivering value at regular interval. To do so it requires short development cycles to allow feedbacks to happen regularly by releasing new features quickly. This is achieved by defining a release plan and several iteration plans in it.

See you next time!

Extreme Programming: User Stories

user-storyAs professional developers, our role is to write high quality code within our applications. Yet this is worthless if it does not provide any value to our customers.

There are not much companies that will hire you to let you work on whatever you want. These businesses have customers that need new features and improvements in the software they buy and use.

It most cases you will work in an industry you know nothing, or almost nothing about. But don’t worry, you will work with people who know it, the business analysts. They know how to provide value for their customers and they need talents to implement it: YOU! You form a whole team.

In order to ease the specification and especially the prioritization of development in an “agile” environment, you can rely on user stories.

User Story

A user story describes a single requirement for the system. It is expressed by the business team and it generally written as a sentence matching the following format:

As a <role>, I want <goal/desire> so that <benefit>

The details are not defined within the sentence because they are likely to change with time even if the main goal will not. Details are discussed during conversations between the business analysts and the development team.

The use of user stories allow the developers to be able to provide a low risk estimate and by extension a budget for the feature. It is focused on the user needs, specific technology details should be excluded (data base schema, algorithm, …).

The role

In the sentence describing a user story a role is defined. By doing so you are able to detect the user of the system. It is likely the person who will know all the details you need to complete the task.

If the user story needs a new User Interface (U.I.) and this person is the final user of it, you should ask him how he wants to use it. Because I think that a UI providing the goal of the user story but with a really bad User Experience (U.X.) is not as valuable as it should be.

The goal

In a user story the goal is the new feature that needs to be created. It defines what the final customer/user wants and needs. This is the part of the system that needs to be well crafted, from a code perspective and from a user experience perspective (see previous section).

The benefit

The last part of the user story describes the benefit. This way you can understand the value it provides to the customers/clients. It can also describes the final result and if you know it, you can test it!

If the benefit of a user story is hard to write down maybe it means that it is not as valuable as you think it is. And therefore there might be others user stories to prioritize first.

In an agile environment such as Extreme Programming (X.P.) the use of user stories allow the business analysts to express their needs for the customers without writing an entire documentation containing every details. They are focused on the user, the goal and the benefit. This way the development team should be able to properly estimate it and they gather the details using a good communication in the whole team.

See you next time!


Image credits:

https://boagworld.com/usability/user-stories/

Extreme Programming: Whole Team

whole-teamExtreme Programming (XP) is one of the agile software development methodologies. Therefore it focuses on short development cycles and to do so it has defined several practices to follow when working with it. In this blog post I will introduce the first one: Whole Team.

As a professional developer I firmly believe in collaboration among a software development team. I believe that is by working together that we are able to create more valuable products.

The developers, the testers, the project manager and the business analysts (sometimes called “product owners”) have a common goal: product value for their customers. This is why they have to work closely with each others and they should be able to speak with each others easily, a good communication is mandatory.

Every role is important in the organization and everyone as a part to play in the project. The business analysts know what has to be done, they represent the customers needs. The developers know how it has to be done, the testers ensure that the quality standards are met and the project manager makes sure that everything runs smoothly.

I know that all of this makes sense, yet sometimes I feel like the common vision is lost in a software development team. Maybe you have experienced the well-known “programmers vs the business” work environment, or maybe the “developers vs testers”.

I know that I have experienced similar situations and I was part responsible for it. Because I only had consideration for my world, where coding is king and everything else is secondary. Now I keep in mind the “big picture”: creating value for the clients. It still requires writing well-crafted code, it is my role in the team. I have to make my teammates understand my point of view and I also have to understand their.

When working in an agile environment, in Extreme Programming for instance, you have to keep in mind that you are part of a whole team. Everyone as a role toward the creation of value.

See you next time!


Image credits:

http://www.branddrivendigital.com/how-to-engage-your-whole-team/

The Law of Demeter

demeterDo not let the title mislead you, today’s article is not about greek mythology. As always I will speak about software development. In my last article I introduced the Tell Don’t Ask principle where it was about object behavior using encapsulation. The Law of Demeter (LoD) is an Object Oriented Programming (OOP) design guideline that fits well with this last principle. This practice uses encapsulation in order to reduce coupling between your components, and therefore it helps you improve your code quality. Here is a definition for the LoD:

Each unit should have only limited knowledge about other units: only units “closely” related to the current unit. Or: Each unit should only talk to its friends; Don’t talk to strangers.

For OOP it can be described with the followings list, which I consider easier to digest:

A method of an object may only call methods of:

  1. The object itself.
  2. An argument of the method.
  3. Any object created within the method.
  4. Any direct properties/fields of the object.

I will now demonstrate the use of the LoD with an example in C#. I will use the famous “The Paperboy and the Wallet” case from the original paper about the Demeter practice. In this example, the paperboy get a payment from a customer who as a wallet.

Initial situation

public class Wallet
{
    public float Value { get; set; }
 
    public void AddMoney(float amount)
    {
        Value += amount;
    }
 
    public void SubMoney(float amount)
    {
        Value -= amount;
    }
}
 
public class Customer
{
    public string FirstName { get; set; }
 
    public string LastName { get; set; }
 
    public Wallet Wallet { get; set; }
}
 
public class Paperboy
{
    public void SellPaper(Customer customer)
    {
        var payment = 2.0f;
        var wallet = customer.Wallet;
        if (wallet.Value >= payment)
        {
            wallet.SubMoney(payment);
        }
        else
        {
            // come back later
        }
    }
}

The Wallet class just stores its amount and exposes two methods to manipulate this amount. A customer has a first name, last name and a wallet. And finally the paperboy sell its good to a given customer using its wallet.

The problems

To me, it does not really looks like a real world scenario, I personally don’t give my wallet to every person I must pay. The paperboy knows that the customer has a wallet and he is able to manipulate it, this can be seen as a Single Responsibility Principle violation. And nothing prevents the paperboy code to do something like this:

customer.Wallet = null;

And maybe the customer’s wallet is already null, and therefore the paperboy’s method has to add a null check to avoid unwanted NullReferenceException.

public void SellPaper(Customer customer)
{
    var payment = 2.0f;
    var wallet = customer.Wallet;
    if (wallet != null)
    {
        if (wallet.Value >= payment)
        {
            wallet.SubMoney(payment);
        }
        else
        {
            // come back later
        }
    }
}

For a simple functionality, I think my code starts to look “heavier” than it should. A modification of the Wallet class will result in an update in the Paperboy class as well, the 3 classes are tightly coupled and it is unnecessary. The paperboy just wants to be paid, no matter if the money comes from a wallet or something else.

Following the Law of Demeter

I will now rewrite the code to fix the previous issues. To do so I will use encapsulation and add a PayAmount() method to the Customer class.

public class Wallet
{
    public Wallet(float initialAmount)
    {
        Value = initialAmount;
    }
 
    public float Value { get; private set; }
 
    public void AddMoney(float amount)
    {
        Value += amount;
    }
 
    public void SubMoney(float amount)
    {
        Value -= amount;
    }
}
 
public class Customer
{
    public Customer()
    {
        FirstName = "John";
        LastName = "Doe";
        _wallet = new Wallet(20.0f); // amount set to 20 for example
    }
 
    public string FirstName { get; private set; }
 
    public string LastName { get; private set; }
 
    private Wallet _wallet;
 
    public float PayAmount(float amountToPay)
    {
        if (_wallet.Value >= amountToPay)
        {
            _wallet.SubMoney(amountToPay);
            return amountToPay;
        }
        return 0;
    }
}
 
public class Paperboy
{
    public void SellPaper(Customer customer)
    {
        var payment = 2.0f;
        var amountPaid = customer.PayAmount(payment);
        if (amountPaid != payment)
        {
            // come back later
        }
    }
}

Now, the paperboy can only access to the first name and last name of the customer, without being able to modify them (for invoicing purposes for example). And he can tell the later to pay a certain amount for the paper without knowing that the money comes from a wallet, the LoD is also known as the principle of least knowledge. The relationship between the Paperboy class and the Wallet class has been removed, the code is less coupled.

With my refactoring, I increased the readability and the maintainability of my code without losing any functionality.

More than simple dot counting

Sometimes the Law of Demeter is stated with a simple phrase: “use only one dot“. This aims to focus on avoiding lines like the following, from the initial example:

customer.Wallet.Value;
customer.Wallet.SubMoney();

The risk with doing this is that you can have a NullReferenceException if the Wallet instance is not initialized, in these examples I used 2 dots. And here it is an indication that the LoD is violated.

But this is not always the case and this is why I consider that the rule should not be sum up to the simple “only one dot” principle. When working with the .NET framework and especially with Linq, it is easier to chain the calls and it has been designed to be used that way. I don’t consider that the following code sample breaks the LoD even if I use more than one dot.

enumerable.Where(o => o.LastName == "Doe").Select(o => o.FirstName).ToList();

The LoD is about loose coupling and encapsulation, it is not about dot counting.

This is the end of my presentation of the Law of Demeter, which I use a lot to avoid unnecessary coupling in my code. Remember that when working with an OOP language you are able to control the way you design your components to expose only what is required and nothing more.

See you next time!


Image credits:

http://sterendenn.deviantart.com/art/Art-Nouveau-Demeter-255076200