Archive

Archive for the ‘Agile’ Category

Mettre de la pression sur le système pour faire apparaître le gaspillage

March 11th, 2010 tremeur balbous posts profile No comments
Mettre de la pression sur le système pour faire apparaître le gaspillage

Mettre de la pression sur le système pour faire apparaître le gaspillage

Afin de faire apparaître les goulots d’étranglement dans le processus de réalisation d’une équipe fonctionnant en Kanban, j’ai proposé de réduire les limites du WIP1

Lors de la mise en place, l’équipe a fixé des limites confortables pour le WIP. Après deux semaines d’utilisation du tableau, l’équipe n’a pas identifié de goulot d’étranglement.
Lorsque j’ai fait ce constat, j’ai proposé au coordonnateur, lorsqu’il a remodelé le tableau à la réception du nouveau tableau, de réduire la capacité de certaines colonnes en plus des modifications prévues lors de la rétrospective.

Cela va bientôt faire trois mois que le tableau Kanban est en place et deux mois que les limites ont été baissées, et nous avons observé des difficultés telles que les suivantes :

  1. Des cartes sont bloquées depuis plusieurs jours et il ne reste qu’un espace disponible dans la colonne pour passer des nouvelles demandes.
  2. Il y a deux cartes dans une case.
  3. Une case ‘blocage spécial’ à été crée pour sortir une carte qui est bloquée et qui n’est plus prioritaire.

En discutant avec l’équipe, il apparaît que la baisse des limites a eu l’effet escompté, puisque avant cette baisse, il y avait suffisamment de place libre pour que de nouvelles cartes puissent passer même si d’autres étaient bloquées.

Content de ce résultat, je comptais proposer à l’équipe de réduire le nombre global de cartes présentes dans le tableau, car actuellement, les limites établies permettent d’avoir un nombre que « je » juge trop important d’items en cours simultanément.
En effet les limites sont établies par étapes du flux de travail, mais les mêmes personnes travaillent sur plusieurs étapes et cela ne force pas les items à sortir le plus vite possible, certains restant même plusieurs jours dans le backlog.

Mais je me suis ravisé car mes solutions ne seront jamais meilleures que celles de l’équipe.
Alors, au lieu de proposer ma solution de réduction du nombre de cartes dans le tableau, j’ai proposé à l’équipe de travailler sur la notion de gaspillage lors d’une rétrospective.

À la suite de cette rétrospective, après avoir identifié l’attente (une carte est souvent en attente dans le tableau) comme l’un des plus gros poste de gaspillage, l’équipe a commencé à mesurer le temps passé par les cartes dans les différentes phases du processus à l’aide de la méthode proposée dans l’article « Flow. Discover Problems and Waste in Kanban ».
J’espère que ces mesures permettront à l’équipe de trouver « ses » solutions pour éliminer le gaspillage, solutions qui rendront la mienne obsolète.

Quels sont les mécanismes que vous mettez en place pour contraindre le système ? Quels sont les résultats que vous obtenez ?

  1. Work In Progress
Instapaper Digg Reddit Twitter Facebook Technorati Favorites Delicious LinkedIn Viadeo Read It Later Slashdot Share/Save

Gartner Predicts 2010: Agile and Cloud Impact Application Development Directions

March 9th, 2010 martin proulx posts profile No comments

Gartner studied the market and attempt to predict trends in their latest report: Predicts 2010: Agile and Cloud Impact Application Development Directions.

As organizations seek to improve productivity and reduce application operating and maintenance costs, we will continue to see an evolution of software development tools, platforms and practices. To take advantage of this, organizations must shift structures and practices while embracing new technologies — a challenging proposition.

Gartner’s analysts (Thomas Murphy and David Norton) predict that by 2012 “agile development methods will be utilized in 80% of all software development projects”. The authors explain that although Scrum will continue gaining in popularity over the coming years, organizations will not be successful in their transition unless they move toward a team-focused culture. As was mentioned in their previous report, very few organizations use a pure-Scrum approach and most rely on an hybrid approach (waterfall and Agile).

The report highlights that organizations struggle to implement true collaboration in the context of globally distributed teams. A situation that has amplified in recent years with outsourcing and off-shoring of software development projects.

In the other hand, the report confirms that teams who have successfully moved to Agile do see productivity improvements especially in “the flexibility of the development team to respond to shifting requirements”. This is especially true for web-based application developments where rapid responses to a changing environment is critical.

The authors point out that organizations need to properly invest in such a transition in order to achieve success.

Organizations that do not make use of key agile practices and do not invest in training and supportive tools’ infrastructure will find that a shift to pseudoagile, while potentially delivering a short-term productivity bump, will end in long-term declines in quality and productivity (…) the promise of four times the improvements in overall productivity has been and will be achieved by select organizations.

Gartner’s report highlights that “development organizations have been making a shift toward agile methods, but this is still slow to move beyond development, and often is a mixture of waterfall practices utilizing an agile or iterative project cycle”. The authors also recommend to “look for opportunities to utilize agile development practices, but recognize that it requires changes and commitment on the part of business and IT”.

Gartner concludes with a few recommendations to help organizations maximize their return from an Agile transition.

  • Recognize the cultural changes that are at the heart of agile.
  • Don’t allow agile excitement to drive cowboy-coding practices.
  • Agile requires discipline.
  • Recognize that scrum is only a partial solution, and focus on a collection of practices.
  • Find tools that enable collaboration and help automate repeatable, consistent practices.

Related documents:

Share/Bookmark

You might be interested in these related posts:

  1. Forrester Reports “Agile Development: Mainstream Adoption Has Changed Agility”
  2. You have the best BI application. Great! Do your users know?
  3. Nobody is interested in Agile

Enfin un bouquin au sujet de scrum en français

March 9th, 2010 françois beauregard posts profile No comments

J’ai reçu il y a environ une semaine ma copie du premier bouquin au sujet de scrum en français. Scrum : Le guide pratique de la méthode agile la plus populaire a été écrit par Claude Aubry. Claude nous offre un regard pratique et lucide au sujet de scrum et de sa mise en oeuvre dans les organisations.

Ayant été en contact à quelques reprises avec Claude depuis quelques années, c’est avec grand plaisir que j’ai signé la préface du bouquin et fait quelques commentaires lors de la lecture du manuscrit.

À quand le prochain bouquin en français au sujet de l’agilité en développement logiciel?

  • Share/Bookmark

_agilely Timer dernière chance avant que ce soit gratuit ;)

March 8th, 2010 françois beauregard posts profile No comments

_agilely Timer permet aux praticiens de l’Agilité ayant un iPhone ou un iPod Touch de gérer efficacement les blocs de temps, les mêlées quotidiennes et les tables rondes. Dans quelques jours l’application sera gratuite. Cela veut dire qu’il ne vous reste que peu de temps pour vous procurer l’application et ainsi faire un don à FIAN, une ONG internationale travaillant au respect et à la réalisation du droit à l’alimentation.

Merci de soutenir cette initiative!
~françois

  • Share/Bookmark
Categories: Agile, Management, Produits, Scrum, Uncategorized Tags:

What consultants don’t tell you before you begin an agile transition – Part 2: Impact on some of the traditional roles

March 8th, 2010 martin proulx posts profile No comments

As a follow up to my previous post, this second post in a series of 4 short articles written in collaboration with my colleagues Stéphane LécuyerJean-René RousseauSylvie TrudelJoël Grenon, and Eric Laramée, addresses the impact an Agile transition typically has on some of the traditional software development roles: the project manager, the architect, the business analyst, and the QA specialist.


One of the first obstacle we routinely encounter in coaching teams through their Agile transition is the mapping of the Scrum roles to the traditional roles. Since Scrum only has three roles (product owner, scrum master, and scrum team), what happens to the project manager, to the architect, to the business analyst, and to the QA specialist after the transition?

Based on our experience, here are possible strategies to properly map the traditional roles to the three roles defined by Scrum.

The Project Manager

Traditionally, the project manager is responsible for determining who, what, and when activities need to be performed and then to ensure the team complies with the plan that was prepared to meet the budget, time and scope constraints.

With the traditional approach, project management is based on compliance with the plan while Agile and Scrum propose a different approach where maximizing the business value is the main vector of project management. Under this new approach, the product manager needs to collaborate with the team members and delegate to them some of his traditional responsibilities since they will determine who does what, and when within the constraints of the project.

In this context, the role of the Scrum Master is to enforce the process and seeks to build an efficient self-organized team. To the question “do we still need a project manager in Agile?”, experience shows us that in most organizations, the answer is yes.

The need for accountability, regulatory compliance and alignment with the framework and IT governance are not covered by the role of the Scrum Master and as such remain the responsibility of the project manager.

However, the project manager needs to adapt its management style and use leadership rather than authority with the team to get things done. In the context of a multi-team organizational structure, the presence of a project manager is also valuable, where he is coordinating the teams and the synchrony between them and between entities external to the project teams.

From our experience, some project managers are more willing to become product owners while others will feel challenged by the role of Scrum Master. In the end, it will be the responsibility of the organization to determine how to redefine the roles and their associated responsibilities.

The Architect

Similar to the project manager, the architect is known to play a different role post-transition compared to that required in traditional development teams. He must act as a consultant to the teams and provide them with the necessary support instead of dictating the rules and guidelines to be followed. The architect should also be familiar with the concepts of emerging architecture, where just enough architecture is planned to allow the team to innovate and find the optimal solutions.

The architect then acts as a catalyst for sharing best practices within the organization. Here is a list of practices summarizing the changes of behavior for the architect:

  • Is an active member of the development teas, helping to build the right software and acting as consultant;
  • Does not attempt to predict the future, he provides a coherent vision but knows that tomorrow’s problems will be easier to solve tomorrow;
  • Is changing its architecture in an incremental way, leaving room for emergence;
  • Does not seek to document everything to perfection, he focuses on a few relevant diagrams and documents the best practices based on his audience;
  • Seeks to validate its concepts through concrete experiences.

Once again, although the role of the architect does change after an agile transition, it remains an important role to be filled.

The Business Analyst

The business analyst is another role that seems neglected by Scrum. To ensure close collaboration between the team and the Product Owner, Scrum ensures that the necessary elements are effectively communicated directly to the team without a formal and complex documentation. However, to ensure continuity of information, we know that functional documentation that is adequate and representative of the software to be developed is essential.

The business analyst becomes a valuable contributor to the Product Owner. The responsibilities of the business analyst are as follows:

  • Supports the Product Owner in gathering and writing the required stories;
  • Does just enough analysis for the functionality to be carried out during the next iteration;
  • Prepares and updates documentation used at the end of each iteration;
  • In collaboration with the QA Specialist, helps determine the quality assurance strategy.

In a multi-team context, the business analyst may be called upon to play the role of Product Owner. He then becomes responsible for core components of the product within the various sub-teams.

The Quality Assurance Specialist

Quality is a fundamental concern in Agile project management and each iteration should produce an increment of quality software. To do this, we recommend incorporating a quality assurance specialist within the Scrum teams, and right from the start of the project. A QA specialist assigned to a Scrum team has the following responsibilities:

  • Participates in planning sessions to raise issues relating to quality;
  • Helps clarify the definition of “Done”‘;
  • Prepares plans for acceptance testing;
  • Validates the increments of product delivered.

Other Roles

As will be presented next week in “Part 3: Impact on the functional and people managers”, managers also get impacted by an Agile transition.

Share/Bookmark

You might be interested in these related posts:

  1. What consultants don’t tell you before you begin an agile transition – Part 1: Impact on the organization
  2. Scrum Role: Scrum Master
  3. You are not doing SCRUM if you don't have a ScrumMaster

What consultants don’t tell you before you begin an agile transition – Part 1: Impact on the organization

March 1st, 2010 martin proulx posts profile No comments

If you have been reading about Agile for a while and are interested in a transition or if you have already initiated a transformation, you have previously heard all the benefits that Agile can bring to your organization but …

Are you aware of the impacts such a transition will have on your organization? On your team? And on yourself? Would you know how to deal with these impacts?

If you believe that implementing Agile within a company simply means reducing documentation, standing up during daily meetings, using whiteboards and post-it notes, and getting rid of the project manager, you will certainly be shocked to see how profound the changes can be.

In a series of 4 short articles written in collaboration with my colleagues Stéphane Lécuyer, Jean-René Rousseau, Sylvie Trudel, Joël Grenon, and Eric Laramée, we aim to highlight some of the most common (and rarely described) impacts an Agile transition can have on an organization. The articles will be published weekly and will cover the following 4 impacts.

  • Part 1: Impact on the organization
  • Part 2: Impact on some of the traditional roles
  • Part 3: Impact on the functional and people managers
  • Part 4: Why a coach is useful

Adopting Agile practices is not a trivial change; it requires support and time to become effective. The use of external coaches, training materials, and internal support groups can greatly increase the speed and success of adoption. - Forrester Reports “Agile Development: Mainstream Adoption Has Changed Agility”.

Many organizations rely on external consultants to help them successfully transition to Agile. Others initiate a small transition after having researched the best practices. Having gained experience from the implementation of Agile within organizations over the last 8 years, we can attest that the impacts related to the establishment of an Agile development approach affect many areas in the organization. Through our experience, we have prepared a high level description of potential impacts you may want to anticipate before getting deep into your transition.

Impact Description
Organizational structure Most large organizations have a traditional hierarchical structure. When launching a new project, project managers must draft team members from various functional departments.

The Agile approach highly recommends restructuring project teams around a dedicated multidisciplinary team.

Decision making and governance The Agile approach seeks to create autonomous and self-organized teams. It invites people managers to apply a different style of leadership to their teams and pushes the decision-making authority to the level closest to the activity being performed.

Under such model, managers provide guidelines to support the decisions rather than act as the ultimate decision makers.

Compensation mechanisms To support the team concept advocated by Agile, compensation mechanisms should avoid individual rewards and foster a compensation model that takes into account the results of the entire team.

The compensation model must be aligned with the business objectives and the commitment to deliver value.

Relationship with customers At the heart of the Agile approach, is the concept of working closely with the customer (Product Owner). The relationship with the business customers will be strongly affected by the Agile transition.

The traditional form of contract and the expected availability of customers must be revised in order to ensure an effective transition.

Development processes The standard development process used within the organizations must be revised and typically “trimmed-down” to match Agile values, principles and practices.

The revision process should include the initial phases of implementation, deployment and operation.

Tools and technology The acquisition of new tools to support Agile project management and software engineering practices is inevitable.

Although the addition of new tools is not in the heart of an Agile transition, it is nevertheless important to maximize the effectiveness in implementing the new process.

Work space organization To foster collaboration within teams, organizations may need to rearrange the workspace in “war room” or remove office partitions to consolidate all the team members.

This in an attempt to improve communications and collaboration between stakeholders and develop a team spirit and strong collaboration.

In addition, easy access to certain items such as whiteboards, removable flip charts, Post-it notes is often recommended.

Behaviors In addition to practical project management and engineering approaches Agile also has a system of values and principles. In addition to ‘Do’ Agile development, individuals are asked to ‘Be Agile’, that is to say, to be collaborative and transparent, be committed and responsible and also to seek excellence.

As Agile approaches are based on greater accountability of individuals and the self-organization of teams, the leadership style of managers and the need to clearly define a shared vision change every day’s actions.

Roles and responsibilities All roles are affected by the arrival of an Agile approach. As will be presented in Part 2: Impact on some of the traditional roles, while some people might gain power, others will feel they are losing.

New skills will be acquired as motivation and engagement of stakeholders will also be affected.

Next week’s post will address more specifically to impact on the role of the project manager, the architect, the business analyst, and the QA analyst.

Share/Bookmark

You might be interested in these related posts:

  1. What consultants don’t tell you before you begin an agile transition – Part 2: Impact on some of the traditional roles
  2. Gartner Predicts 2010: Agile and Cloud Impact Application Development Directions
  3. Currently recruiting Agile consultants

Gartner’s “The Current State of Agile Method Adoption”

February 25th, 2010 martin proulx posts profile No comments

As part of a market research for one of our customer, I came across this report published by Gartner in December 2008.

As the pace of agile adoption increases, development organizations must understand the different levels of agile maturity. CIOs and product and development managers need to assess where they fit on the maturity scale, and which level offers the biggest return in their organizations.

The report presents the 6 levels (from 0 to 5) of Gartner’s Agile Maturity Model and corrects a few myths.

  • Agile adoption and penetration rates are being overestimated. Although the number of companies that are adopting agile practices is, indeed, reasonably high, most organizations use agile in a very small percentage of their overall work.
  • An agile maturity framework is necessary to help make the case for adoption, process improvement and benchmarking.
  • Current adoption rates for agile and iterative methods are between 15% and 25%, when taking into account penetration and maturity, with waterfall still the dominant approach. The pace of agile adoption is increasing.

The report concludes that :

As part of an agile readiness assessment, IT development organizations should access their current agile practice maturity at technical, project management and organizational levels. Practices should be assessed for, among other things, their effectiveness and adoption levels in the organization. Adoption should follow initial pilots, and should normally be Level 2, with the aim of developing a consistent set of agile practices at Level 3.

RECOMMENDED READING

Share/Bookmark

You might be interested in these related posts:

  1. Gartner Predicts 2010: Agile and Cloud Impact Application Development Directions
  2. Forrester Reports “Agile Development: Mainstream Adoption Has Changed Agility”
  3. Will the current economic landscape prevent the launch of new BI initiatives?

Pendant ce temps-là, à Boulogne…

February 23rd, 2010 Emmanuel Gaillot posts profile 7 comments

Je profite d’un moment de répit pour sortir le nez du trou et annoncer que le site web sur lequel je travaille comme (extrême) développeur pour Delasource est en ligne, ouvert au public depuis deux semaines.

Il s’agit d’un jeu concours pour adolescents (Français ou Espagnols) dont le premier prix est de pouvoir rencontrer Taylor Lautner (ceux à qui le nom ne dit rien, ne culpabilisez pas — le monde des stars pour ados est vaste et Google peut vous aider à combler vos lacunes ni vu ni connu) et le représenter lors d’un événement auquel il ne pourra pas assister. D’être, en un mot comme en mille, un “ambassadeur de star”. Au passage, il est question de faire plein de pub sans s’en apercevoir pour le compte de diverses entreprises et d’envoyer des SMS et des MMS comme si on n’avait rien de mieux à faire.

http://ambassadeurdestar.com
http://star-ambassador.es

Le projet est mené en eXtreme Programming, dans les règles de l’art. Le site est développé en Ruby on Rails avec TextMate, sur MacOS donc. Nous ajoutons des fonctionnalités tous les jours, il y a au moins une  mise en production par jour depuis l’ouverture au public. L’équipe compte actuellement 6 programmeurs (dont le responsable produit), 2 graphistes, 3 modérateurs et une poignée de stake-holders. Tout ce monde travaille dans un ancien atelier réhabilité à Boulogne, dans une même pièce. L’application web est développée en TDD (à l’exception des vues). Elle est actuellement couverte par 951 assertions, réparties sur 563 tests automatisés qui s’exécutent en 35 secondes environ.

En 4 mois de boulot, nous avons consommé 150 pages de flipchart, 15 marqueurs, 100 fiches cartonnées, 2000 post-its de couleurs et tailles variées, 10 stylos feutre, 5 stylos bic, 2 bloc-notes, 50 feuilles A4, un playmobil et 300 viennoiseries.

Ces mois de travail en équipe m’auront amené à tisser des liens marqués d’une grande sympathie et d’un profond respect pour  mes coéquipiers : un ancien DJ ceinture noire d’aïkido à l’entrepreneuriat dans le sang, un concepteur de jeux vidéo au calme exemplaire, un breton philosophe ancien prof de maths, un polonais increvable et un freelance esthète à qui l’écriture de logiciel importe (beaucoup).

Je suis particulièrement fier du résultat que nous avons atteint, autant pour toutes les bonnes décisions que nous avons prises à temps que pour tous les obstacles que nous avons rencontrés et dont nous avons su tirer le meilleur parti.

… et je me disais que vous auriez peut-être envie de vous réjouir avec moi :)

  • Share/Bookmark

The “Best Agile Work Space” Contest (The BAWS Contest)

February 17th, 2010 martin proulx posts profile No comments

A few days ago, we invited representatives from a potential customer over to visit our office. They are seriously considering a transition to Agile but some of the managers had questions with regards to what an Agile work space could look like. The potential customer is a large insurance company and like most insurance companies, people working there are used to a traditional (very traditional) work space. We could see they had some reservations about the open-concept before coming for a visit.

Their visit lead me to wonder what other Agile work spaces could / should look like, so I came up with the idea of launching a friendly contest…

The “Best Agile Work Space” Contest

I invite you to email me a picture of your Agile work space (martin [at] analytical-mind.com). In the spirit of sharing best practices and getting ideas from each other, I will post your pictures and your company’s name for people to get inspired. You can also share with everyone what makes your work place the Best Agile Work Space. We’ll even ask people to vote!

Let the contest begin to determine the “Best Agile Work Space“. Tell your friends to email their pictures.


To launch the contest, here are a few pictures of our work place.

Best Agile Work Space - Pyxis' Office

Best Agile Work Space - Pyxis' Office

Best Agile Work Space - Pyxis' Office

Best Agile Work Space - Pyxis' Office

Best Agile Work Space - Pyxis' Office

Best Agile Work Space - Pyxis' Office

Examples of other Agile Work Spaces found on the web

Windows are often a scarce commodity and are doled out to an organization’s favored employees. One of the nice things about an open workspace is that windows are shared. Even if the view is only of our parking lot and can only be seen across three messy desks, at least I can see the window and some natural light - The Ideal Agile Workspace | Mike Cohn’s Blog – Succeeding With Agile®.

Our New Agile Workspace - Our New Agile Workspace on Flickr – Photo Sharing!.

I started to respond in his comments and then remembered that it would be better to capture our workspace on video to share with others.  I am hoping other agile shops will do the same.  We are always eager to see how others are doing things so we can continue to improve - Attempting to Achieve the Ideal Agile Workspace | Derek Neighbors.

Ward Cunningham among others was a big influence early on in making it happen.  The patterns & practices team workspace is optimized for agile development practices.  The workspace features writeable walls, configurable workspace, speaker phones, projectors, focus rooms, and a customer room - Shaping Software » Blog Archive » Microsoft patterns & practices Agile Workspace Tour.

Share/Bookmark

You might be interested in these related posts:

  1. What consultants don’t tell you before you begin an agile transition – Part 1: Impact on the organization
  2. Share best practices for an Agile BI project
  3. Day one in an Agile environment

FizzBuzz à la façon LINQ

February 15th, 2010 ernst perpignand posts profile No comments

ModèleDernièrement mes collègues et moi exécutions le Kata FizzBuzz dans le cadre de notre Dojo pratiques d’ingénierie. L’objectif était de pratiquer le développement piloté par les tests. Je dois avouer que ce fut fort amusant et la solution à laquelle nous sommes arrivés est tout à fait adéquate et présente un modèle objet élégant qui résoud le problème.

La séquence FizzBuzz est générée par la méthode CountTo de la classe FizzBuzz. Cette dernière utilise un ensemble de règles qui vérifient si elles s’appliquent et transforment, le cas échéant, l’entier question soit en “Fizz”, “Buzz” ou “FizzBuzzz”.

class FizzBuzz
{
    private readonly IRule[] _rules = new IRule[] {
        new FizzBuzzRule(),
        new BuzzRule(),
        new FizzRule()
    };

    private readonly IRule _defaultRule = new NumberRule();

     public string[] CountTo(int upperBound)
    {
        var sequence = new List();

        foreach (var n in NumbersUpTo(upperBound))
        {
            sequence.Add(Interpret(n));
        }

        return RespondWith(sequence);
    }

    private static IEnumerable NumbersUpTo(int n)
    {
        for ( int i = 1; i <= n; i++)
        {
            yield return i;
        }
    }

    private string Interpret(int n)
    {
        foreach (var rule in _rules)
        {
            if (rule.Applies(n)) return rule.Apply(n);
        }
        return _defaultRule.Apply(n);
    }

    private string[] RespondWith(List result)
    {
        return result.ToArray();
    }
}

La classe FizzRule est un exemple d’implémentation d’une rèlge.

class FizzRule : IRule
{
    public bool Applies(int number)
    {
        return ShouldSayFizz(number);
    }

    private static bool ShouldSayFizz(int n)
    {
        return IsDivisibleByThree(n) || ContainsThree(n);
    }

    private static bool IsDivisibleByThree(int number)
    {
        return number % 3 == 0;
    }

    private static bool ContainsThree(int n)
    {
        return n.ToString().Contains("3");
    }

    public string Apply(int number)
    {
        return SayFizz();
    }

    private static string SayFizz()
    {
        return Fizz;
    }

    private const string Fizz = "fizz";

}

Plus tard, je me suis demandé de quoi aurait l’air la solution si j’utilisais les fonctionnalités du langage C# 3.0 telles que LINQ, les expressions lambda et les méthodes d’extension. Avec notre batterie de tests comme garde-fou je me suis lancé dans une session de refactorisation au bout de laquelle je suis arrivé à la solution que je présente plus loin.

Les premières pistes que je choisis d’explorer sont les méthodes que Resharper suggère de changer en méthodes statiques. En fait, les méthodes statiques me font toujours penser à des méthodes utilitaires qui en général sont très réutilisables. C’est le cas par exemple des méthodes IsDivisibleByThree et ContainsThree de la classe FizzRule plus haut. Je les rassemble donc dans la classe IntExtensions après avoir introduit un peu de généricité pour qu’elles soient utilisables également dans la classe BuzzRule.

public static class IntExtensions
{
    public static bool Contains(this int n, int number)
    {
        return n.ToString().Contains(number.ToString());
    }

    public static bool IsDivisibleBy(this int number, int dividend)
    {
        return number % dividend == 0;
    }
}

Avec ces modifications, la méthode ShouldSayFizz se lit comme suit:

private static bool ShouldSayFizz(int n)
{
    return n.IsDivisibleBy(3) || n.Contains(3);
}

Je suis content car la lisibilité du code n’en souffre pas. Je m’attaque de la même façon à la méthode NumbersUpTo de la classe FizzBuzz. J’en fais une méthode d’extension que je rajoute à la classe IntExtensions. Je prends le soin de renommer la méthode FirstNumbers pour une meilleure lisibilité du code client qui se lira

foreach(int number in n.FirstNumbers()) { … }

Cela me rappelle mon cours d’analyse et la série des n premiers nombres entiers… En fouillant un peu dans MSDN, je retrouve comment générer une suite d’entiers grâce à la classe Ennumerable et je modifie mon implémentation en conséquence. J’obtiens le résultat suivant

public static class IntExtensions
{
    public static IEnumerable FirstNumbers(this int n)
    {
        return Enumerable.Range(1, n);
    }

    public static bool Contains(this int n, int number)
    {
        return n.ToString().Contains(number.ToString());
    }

    public static bool IsDivisibleBy(this int number, int dividend)
    {
        return number % dividend == 0;
    }
}

Avec ces méthodes utilitaires hors de la classe FizzRule, la responsabilité de celle-ci devient plus évidente et je la simplifie pour arriver au résultat suivant

class FizzRule : IRule
{
    public const string Fizz = "fizz";
    private const int Three = 3;

    public bool AppliesTo(int number)
    {
        return number.IsDivisibleBy(Three) || number.Contains(Three);
    }

    public string Apply(int number)
    {
        return Fizz;
    }
}

Une bonne chose de faite! Je tourne mon attention vers la classe FizzBuzz. Même si j’ai sorti la génération des nombres entiers hors de cette classe, elle a encore trop de responsabilités: maintenir la liste des règles FizzBuzz, appliquer les règles qui conviennent, formater le résultat. C’est une violation évidente du principe de responsabilité unique (Single Responsibility Principle) de l’oncle Bob. Je décide donc séparer tout ce qui touche à la transformation FizzBuzz dans une classe à part. Les règles et tranformations FizzBuzz sont maintenant rendues dans la classe FizzzBuzzExtensions. J’ai changé l’implémentation pour utiliser LINQ étant donné que le résultat est plus compacte et tout de même très lisible.

static class FizzBuzzExtensions
{
    internal static IEnumerable AsFizzBuzzSequence (this IEnumerable sequence)
    {
        return sequence.Select(numeral => Transform(numeral));
    }

    private static string Transform(int n)
    {
        return FirstRuleThatApliesTo(n).Apply(n);
    }

    private static IRule FirstRuleThatApliesTo(int n)
    {
        return Rules.First(r => r.AppliesTo(n));
    }

    private static readonly IRule[] Rules = new IRule[] {
        new FizzBuzzRule(),
        new BuzzRule(),
        new FizzRule(),
        new NumberRule()
    };
}

L’astuce d’encapsuler cette fonctionnalité en arrière d’une méthode d’extension facilite grandement la lecture de la classe FizzBuzz qui devient

class FizzBuzz
{
    public string[] CountTo(int n)
    {
        return RespondWith(n.FirstNumbers().AsFizzBuzzSequence());
    }

    internal static string[] RespondWith(IEnumerable result)
    {
        return result.ToArray();
    }
}

Séparer ainsi les responsabilités dans différentes classes a grandement augmenté la clareté du design. De plus l’utilisation de LINQ et des méthodes d’extension fait en sorte que le code est très compacte quoique très expressif. À vous d’en jugez. Voyez-vous d’autres pistes d’améliorations ?

  • Share/Bookmark