Accueil > Non classé > Dé-switcher n’est pas jouer

Dé-switcher n’est pas jouer

Amis utilisateurs de Checkstyle, avez-vous remarqué que les switch sont des sources inépuisables de complexité cyclomatique ? Sans parler de leur équivalent pour les objets, les if () {} else if (){} else if (){} else if (){} à répétition.

Parmi les reproches récurrents faits aux switch, il y a le fait qu’ils ne respectent pas le principe Ouvert/Fermé. A chaque ajout de nouvelles valeurs, il faut modifier tous les switch qui les manipulent.


Il est toujours possible de se passer d’un switch. Un moyen simple est d’utiliser une Map. Ainsi, le code suivant :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public String getMessage(int messageCode) {
    String message;
    switch (messageCode) {
        case 42:
            message = "the Answer to the Ultimate Question of Life, the Universe, and Everything.";
            break;
        case 13:
            message = "Good luck!";
            break;
        // [...]
        default:
            throw new IllegalArgumentException("Unknown code");
    }
    return message;
}

devient :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private final Map<Integer, String>  messagesByCode = new HashMap<Integer, String>();

private void initMessagesByCode() {
    messagesByCode.put(42, "the Answer to the Ultimate Question of Life, the Universe, and Everything.");
    messagesByCode.put(13, "Good luck!");
    // [...]
}

public String getMessage(int messageCode) {
    String message = messagesByCode.get(messageCode);

    if (message == null) {
        throw new IllegalArgumentException("Unknown code");
    }

    return message;
}

Cela fonctionne aussi si le switch (ou les if/else) contient du code à exécuter qui varie suivant les cas. Ainsi :


1
2
3
4
5
6
7
8
9
10
11
12
public void doAction(String action) {
    if ("syso".equals(action)) {
        System.out.println("Yeah");
    } else if ("syserr".equals(action)) {
        System.err.println("Yahoo");
    } // [...]
    else {
        throw new IllegalArgumentException("Unknown action");
    }
}
// [...]
doAction("syso");

devient (j’en conviens, des first-class functions simplifieraient le code) :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private final Map<String, Runnable> actionsByName = new HashMap<String, Runnable>();

private void initActionsByName() {
    actionsByName.put("syso", new Runnable() {
        public void run() {
            System.out.println("Yeah");
        }
    });
    actionsByName.put("syserr", new Runnable() {
        public void run() {
            System.err.println("Yahoo");
        }
    });
}

public void doAction(String action) {
    Runnable runnable = actionsByName.get(action);

    if (runnable == null) {
        throw new IllegalArgumentException("Unknown action");
    }

    runnable.run();
}
// [...]
doAction("syso");

Clairement, si ce type de modification permet de se passer de switch sans modifier la signature des méthodes, elle n’est pas idéale. Une bien meilleure option ici serait de se souvenir que Java est un langage orienté Objet, et utiliser le polymorphisme pour implémenter le pattern strategy ;-) :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public interface Action {
    void doAction();
}
// [...]
public void doAction(Action action) {
    action.doAction();
}
// [...]
public class Syso implements Action {
    public void doAction() {
        System.out.println("Yeah");
    }
}
// [...]
public class Syserr implements Action {
    public void doAction() {
        System.err.println("Yahoo");
    }
}
// [...]
doAction(new Syso());

On pourrait enfin utiliser les possibilités offertes par les enum Java :


1
2
3
4
5
6
7
8
9
10
11
12
13
14
public enum ActionEnum implements Action {
    SYSO {
        public void doAction() {
            System.out.println("Yeah");
        }
    },
    SYSERR {
        public void doAction() {
            System.err.println("Yahoo");
        }
    };
}
// [...]
doAction(ActionEnum.SYSO);

J’espère que ce court article vous aura convaincu qu’il est tout à fait possible de se passer des switch. Un code comprenant des switch et autres if () {} else if (){} est en général tout sauf simple et maintenable.
Dans Clean Code, Uncle Bob Martin conseille d’ailleurs d’encapsuler le code lié aux switch dans des fabriques abstraites, afin de ne pas les laisser polluer le reste du code.

Edit (03/08/2010) : dans le même domaine, vous pouvez lire cet article sur le Refactoring par la pratique.

Share
  1. Raphaël LEMAIRE
    25/06/2010 à 09:38 | #1

    Bon article.

    On attend avec impatience de pouvoir améliorer l’astuce de la Map avec des closures comme valeurs.

    Il existe un site contre les ifs qui devraient être du polymorphisme :

    http://www.antiifcampaign.com/

  2. 25/06/2010 à 11:27 | #2

    Doublé par Raphaël, je voulais faire référence à http://www.antiifcampaign.com/

  3. ParrainGeek31SansIPhone
    25/06/2010 à 16:46 | #3

    C’est une transmission de pensée(s), je viens de remplacer un gros bloc switch case par
    final EnumMap sortTranslator
    = new EnumMap(SortEnum.class);
    sortTranslator.put(SortEnum.REFERENCE, “a.reference”);
    // etc….
    Et mon filleul vient de m’envoyer le lien de ton site !
    PS: noter que j’ai fait une EnumMap et pas une Map pour éviter de me baser sur le equals/hashCode car je travaille avec des enum.

  4. Neko
    01/07/2010 à 12:12 | #4

    Salut à toi Pierre Yves (salut aux autres lecteurs)

    Je ne suis absolument pas d’accord avec ton article (enfin en partie).
    Tout d’abord, si le switch existe depuis si longtemps, c’est peut être parce que c’est plus qu’une structure de contrôle; je veux dire, des optimisations sont faites derrière par le compilateur. (Certes, le Java est un cas légèrement différent de part sa VM, et je ne sais pas programmer dans ce dernier, mais je pense que mon post est quand même valable)

    Actuellement, un swich avec beaucoup de cas différents est automatiquement remplacé (quand c’est possible) par un pointeur sur fonctions, justement pour éviter une batterie de if/else.

    Je t’invite à lire cet article http://www.safercode.com/blog/2008/10/28/optimizing-switch-case-statements-in-c-for-speed.html qui parle de l’optimisation des switch/case en C.

    Ensuite je voudrais parler de ton point sur le pattern “strategy”.
    C’est un choix dangereux, car si ta classe est lourde, tu n’as pas forcément envie d’en faire X sous classes pour implémenter quelques stratégies, je pense donc que ce genre de patterns est à utiliser avec parcimonie.

    De manière générale, il ne faut pas diaboliser les structures de contrôles if/else et switch.
    Je pense qu’il serait plus approprié d’apprendre à les utiliser avec parcimonie, et surtout efficacité, car ils ont tous des avantages/désavantages selon les situations.

    Un code contenant des switch et if/else n’est pas forcément difficile à maintenir (même si, ça à souvent l’air d’être le cas), ou compliqué à comprendre.

    Voila, bonne journée à toi.

  5. 01/07/2010 à 21:51 | #5

    Bonjour,

    Autant je comprends et approuve fortement la première partie de l’article, autant je ne comprends pas l’utilité du pattern strategy dans ce contexte.

    Quelle différence entre doAction(new Syso()); et new Syso().doAction(); ?

    Le switch permet de relier un ensemble de valeurs à un ensemble d’exécutions. Si on dispose déjà de l’exécution, on n’est plus tellement dans le cadre d’un switch.

    Ce billet m’a toutefois donné envie d’exposer une technique que j’utilise parfois en C# pour éviter la maintenance manuelle d’un “Map” centralisé : http://agilitateur.azeau.com/post/2010/07/01/Un-switch-%C3%A9volutif-en-C
    Cela se base sur le concept d’attributs dans .NET
    Je connais mal java mais est-ce que la gestion des “case” d’un “switch” via des annotations y serait possible ? Et aurait elle un intérêt ?

    Concrètement, est-ce que l’on pourrait écrire quelque chose comme (syntaxe non garantie) :

    @Case(“syso”)
    public class Syso implements Action {
    public void doAction() { System.out.println(“Yeah”); }
    }

    @Case(“syserr”)
    public class Syserr implements Action {
    public void doAction() { System.err.println(“Yahoo”); }
    }

    et avoir un mécanisme générique qui, étant donné une string “syso” ou “syserr” exécuterait le “doAction” correspondant ?

  6. 02/07/2010 à 12:11 | #6

    @Oaz
    Décidément, cet article semble déchaîner les passions dans les commentaires :-D ! Dommage que Pierre-Yves ne puisse pas répondre à cause d’une vacancite aigüe…
    Ton idée m’a donné envie de tester la faisabilité d’un @Case en Java, et bien évidemment c’est possible. J’ai documenté ça sur un autre blog : http://foobaz.free.fr/blog/?article7/un-switch-annote-en-java

  7. Denis VAUMORON
    07/07/2010 à 21:07 | #7

    Le @Case est pas mal, mais en casse-pieds de service, je note tout de même que tu aurais pu utiliser la méthode asSubclass pour ta méthode isA :

    private boolean isA(Class clazz, Class class1) {
    try {
    clazz.asSubclass(class1);
    } catch (ClassCastException cce) {
    return false;
    }
    return true;
    }

  8. 10/07/2010 à 11:56 | #8

    Mouais, en râleur de service je trouve ça moyennement “propre” d’appeler une méthode en sachant qu’elle peut me jeter une exception dans la face, même si je l’attrape… Mais pour le coup j’admets que ça simplifie le code : on n’a pas besoin de tester les deux types d’extension, à savoir super-classe ou interfaces.

  9. 25/11/2019 à 03:56 | #9

    Bathing Suits
    This is not a guarantee. Some people are givers and some are takers.
    It’s best to be a balance of both. These needs will determine the size, shape and quality
    of the tent you select. Keep in mind that with tents, bigger isn’t necessarily better you’ll have to lug it to your campsite, after all.
    Be sure to try your tent out at home to detect
    any problems so your camping trip doesn’t turn into
    a nightmare.

    wholesale bikinis If Blizzard woudl actually
    release the numbers I could calcluate it out but the additional factor is we don know what is the
    critical number at which the game will give you duplicates again. I haven recieved a single duplicate since they overhauled the system but I have a lot of items I could still obtain. 1 point submitted 2 days ago.
    wholesale bikinis

    Sexy Bikini Swimsuit There are several very well respected DGI investors who contribute to this website who remain fully invested at
    all times. They’re maximizing their compounding potential.

    But, being so highly exposed to equity leaves them little protection to
    the downside, so there is obviously some risk/reward to
    consider.. Sexy Bikini Swimsuit

    bikini swimsuit Speakers will have particular frequency response, a studio
    monitor would ideally have as flat a response as possible,
    giving as honest representation of the signal as possible, whereas a
    celestion guitar amp cone wouldn give a flat response, the speaker itself is shaping the character of the sound.
    The impedance thing I think is more to do with matching the
    right amount of resistance to the power output of your
    amplifier. More to do with the engineering of your HiFi system than anything else.
    bikini swimsuit

    Women’s Swimwear Musa and Maehwa were supposed to be the most mobile class.
    To quote someone from the discord, “a maehwa with 1 tri khalk and bis boots crystals and urugon tested dashing and witchards mystics strikers zerk tamer outrun him”.
    This is because how quickly our stamina is depleted, not to mention them being used for other skills..
    Women’s Swimwear

    wholesale bikinis I most certainly did! i had the
    very same attitude. I ate what i wanted, when i wanted if i wanted doritos for breakfast, i had some.
    If i wanted a pb sandwich at 2am, i had it!
    i was always SOOOO hungry when i was pregnant! i would wake up at
    5am just because my stomach was growling, go eat a granola
    bar, then go back to sleep. wholesale bikinis

    beach dresses Rogues dont have bushing seats to keep the hanger where it needs to be for proper
    turning geometry. The insert bushing is what does
    that. Because its at the dead center of the hanger pivot axises.
    The most difficult character to animate from a hair standpoint was Violet.
    She remained an “unsolved research project” well into the production of
    the film, due to her long, flowing hair the bane of an animator’s existence.
    In fact, no one had ever animated this kind of hair before for a CG film.

    beach dresses

    The hair was so dark that you could see it under my skin, even right after I
    shaved, and grew so fast that I literally got a five o’clock
    shadow. I never wore sleeveless blouses because of the dark
    shadow. I spent a half hour every singe day just
    shaving myself so I wouldn’t look like a yeti..

    The maximum loan to value ratio for permanent commercial mortgages is 75%.
    The maximum loan to value ratio for land development loans is 70% and for unimproved land is
    65%. The Bank also offers home equity loans secured by the borrower primary residence,
    provided that the aggregate indebtedness on the property does not exceed
    80% of its value for loan commitments greater than $100,000.

    I will teach these trespassers the redemptive power of my Janus key.
    They will learn it simple truth. The Tenno are lost, and they will resist.
    There is an underlying problem here. Maybe check out the book “The Subtle Art of Not Giving a Fck.” Or talk to your therapist about it.
    Maybe preferably the latter.

    cheap bikinis Do not link to or post screenshots of other subreddits for the sole purpose
    of brigading, vote manipulation, or to attack their fan base or specific users.5c.
    Posting about bans obtained from other subreddits will result in a ban here
    as well.6. No personal information. cheap bikinis

    wholesale bikinis I have a very poor poker face, and my anger
    was evident. I unkindly told Crevice that from
    now on, I will no longer be trying to win, just to make sure he lost.
    I told him I would do my best to destroy his night, as he had destroyed mine.
    Brake fluid resides in a sealed, air tight reservoir on top of the
    master cylinder. As the brake fluid level drops, air moves
    in to fill the void. Wait a minute didn’t we just say that the system was air tight?
    Well, unfortunately, air does get into the reservoir over time
    and it eventually makes its way into the rest of the braking system including your brake lines.
    wholesale bikinis

    bikini swimsuit As many of my followers know, I’ve been an analyst focused on Asia for well over a decade.
    Japan has a lot of interesting companies, but the country is also chock full of another type of company: consumer electronics companies with no moats.

    Canon (NYSE:CAJ), Casio (OTCPK:CSIOY), Fujitsu (OTCPK:FJTSY),
    JVC Kenwood (OTCPK:JVCZY), Kyocera (NYSE:KYO), NEC (OTC:NIPNF), Nikon (OTCPK:NINOY), Olympus
    (OTC:OCPNF), Panasonic (OTCPK:PCRFY), Sharp (OTCPK:SHCAY)
    and Toshiba (OTCPK:TOSYY) are the best examples of Japanese consumer
    electronics company with very little moat..

    bikini swimsuit

    wholesale bikinis Swishing them in plain tap water reduced bacterial counts by 66 to 94 percent, depending on species type.
    However, hundreds of recoverable bacteria remained on the fabric.
    In comparison, rinsing with bleach or Lysol solutions
    knocked counts down to less than a tenth of a percent of their original numbers..
    wholesale bikinis

    cheap swimwear The main differences are that cardio is much better for my legs,
    lungs and my heart. Weight lifting is better for my
    abs, back, shoulders, triceps, biceps and chest.
    Cardio can burn more calories while you are doing it. And once they
    start praying there, it is considered hallowed ground and can’t be taken away.
    Ever. That’s why we’re having this tug of war between New Yorkers and the Islamic people.”. cheap swimwear

    cheap bikinis For those who like to be free when running, this gadget is for you. Fitbit One is a sleek gadget that you can clip on easily. You don’t have to wear it on your wrist continuously. If you grew up in the era of the Apollo program, the space shuttles and the Hubble telescope, you’re probably accustomed to thinking of space exploration as involving pieces of hardware with astonishing price tags, single, narrowly focused missions and short life expectancies. But in an era in which NASA is under increasingly tough budgetary pressure, today’s space scientists no longer have a blank check to explore the cosmos. Instead, they’ve got to use their ingenuity to make the most of limited resources for example, by bringing a mothballed satellite out of hibernation and repurposing it for a new mission.. cheap bikinis

    wholesale bikinis Sexual harassment is a big issue, and laws are very strict. You could end up not only getting fired, but also subjecting your office to liability too. Bottom line: you should find someone to date outside of your workplace.. In an attempt to answer this, I compiled the table shown at the end of the article. It shows that out of the 46 acquisitions proposed since June (that I was able to count there may be more), 32 of them involve at least one class action lawsuit. That’s a whopping 70% of all deals! So, what gives?. wholesale bikinis

    Women’s Swimwear If it happens again I say “thanks for your suggestions,
    but I not looking for advice on my skincare routine, I just need foundation today”, or maybe “thanks for
    the help I good for now”. My heart goes out to you cause I know how it feels to be belittled for something out of my control, but remember you are beautiful just the way you are. Imperfections are what make us unique and those rude comments make us stronger and more resilient at the end of the day Women’s Swimwear.

  10. 25/11/2019 à 09:09 | #10

    Monokinis swimwear
    Barbie and Fashion QueenIn 1961, along with manufacturing the Ponytail models, Mattel introduced Barbie with a short, bouffant hairdo called the “bubblecut” (stock 850).
    The doll (with the same stock number as the Ponytails) was sold wearing a red
    or blue jersey type swimsuit with pearl earrings. A popular seller, “Bubblecut” Barbie,
    in a variety of hair, lip and nail colors, was manufactured until
    1966..

    Sexy Bikini Swimsuit Originally, Forever 21 only sold clothes for women, but
    later expanded to sell menswear. Most Forever 21 stores now sell clothes for men and women, including
    plus size clothing for women. District Court
    Judge Manuel Real, Forever 21 responded with a defamation suit in 2002.[13] Attorney Robin D..
    Sexy Bikini Swimsuit

    Bathing Suits As he runs, he runs into a man in a parked
    car. He says they do this every week and soon they will change.
    He tells him to put this wig on so that they think you are someone else.
    And the other type is the Electric Forklifts which requires occasional charging
    because they are mainly battery operated. Considering
    all these factors for a forklift truck, some factors like tires, model, capacity to lift the load
    to a certain height, etc, everything matters when you decide to buy this machine.

    So, decide for yourself whether you want to lease, rent or fully buy the forklift
    to serve your needs.. Bathing Suits

    Monokinis swimwear I’m 21 wks pregnant with our first
    kiddo. The first trimester was so hard for me.
    Couldn’t eat, couldn’t cook, couldn’t do anything but drag my ass to
    work and come home and sleep. Direct). By assuming EBIT margins
    for direct are 600bps higher than in store (management confirmed on 4Q17 call that “our online businesses are more profitable than our store based businesses.”),
    we are able to estimate the cost incurred per VS store in the US.
    For example, we know that EBIT margins for VS overall is
    12.6% in 2017, and we know that direct sales represented 20% of total VS sales.

    Monokinis swimwear

    beach dresses Welcome to the IAMGOLD 2015 Second Quarter
    Operating and Financial Results Conference Call and Webcast.
    As a reminder, all participants are in listen only mode.
    And the conference is being recorded. I mentioned to another guy
    I work with that not having anyone else in the house for the weekend has been freaking me out since I been hearing
    every little noise. She took the bait and shortly after, when no one was near by, she asked me, “what are your plans for this evening?” I waited
    a little while and when we were about to leave asked her, “what are you about to go do?”
    I guess she didn hear me and asked me to repeat
    myself, “Uhh, what?” I repeated my question, but could tell
    she was unsure of what she should do. Before I could get, “come hang out with me” out, she says “Um. beach dresses

    Cheap Swimsuits How far will forensic accountants go to obtain information? It all depends on the nature of the case. In criminal cases, they usually work with law enforcement and the district attorney’s office. Just as with other types of evidence, the prosecution must obtain search warrants and subpoenas to locate financial information and compel knowledgeable people to give interviews about the situation in question.. Cheap Swimsuits

    Monokinis swimwear Just pick one side of the pool and always breath facing that side.old97ss 1 point submitted 6 days agoF2p here and for me that means i only use a few classes and dust anything from the other classes when i want somethingNo hunter. Rogue. Druid. A few months later Kunal and Sam meet in court, where they are picking up residency permits. Recognising the value of their friendship with Neha and each other, they reconcile. They find Neha at a fashion show and try to apologise, but she refuses to see them. Monokinis swimwear

    one piece swimsuits This procedure is called judicial waiver. Some other states adopt a mechanism called statutory exclusion, in which certain grave offenses (like first degree murder) committed by juveniles have to be filed in criminal courts instead of juvenile courts. Concurrent jurisdiction is another mechanism that is used for trying juveniles in criminal courts.. one piece swimsuits

    bikini swimsuit You may want to be extra cautious in this regard because a silly comment of yours that may have been in jest, may end up hurting her feelings or making her over think it. It is okay if you don’t understand this, all you need to do is choose your words extremely carefully if you are going to try to engage in a teasing or mocking conversation with your shy woman. At best, avoid it.. bikini swimsuit

    one piece swimsuits Oriental Media’s dynamic interactive marketing solutions provide immediate, measurable and tangible results for its clients and customers. E[acute accent]Oriental Media Communications and its affiliates are located in Shanghai China. For additional information, please contact Mr.. one piece swimsuits

    cheap bikinis We are basically stuck with Rachel and Donna, who, used to fit their roles perfectly, but now through whining and crying have suddenly got everything they wanted and have been propelled to positions that they are not fit for.How does Rachel, who is a law STUDENT, know anything about mentoring associate LAWYERS, and how the fuck does Donna go from secretary to senior partner. And her argument was that CEO of other law firms aren lawyers either? Uh. Yeah because they are CEO with years of schooling and management experience, not fucking secretaries?If you know anything about LLP you “buy in” to the firm (Donna 500k check (btw if she had
    500k to spare without taking out a loan, she really needs to stfu and stop crying about superficial titles)) because you are buying a piece of the firm, meaning you also take a piece in the firm revenues.
    cheap bikinis

    This was last years palette. I didn get it during the holiday season and I completely regretted it.
    Around April, Tarte had a crazy sale on the website and I was able to pick up the bling it on palette for $30ish dollars.
    As Jason, you are expected to kill as many Counselors as
    you can before time runs out or they all escape. You technically are successful even if you killed at least one Counselor.
    Quickly make yourself familiar with what each map looks like and
    the more game time you have as Jason, you will notice the common areas you
    can find counselors as will as common counselor behavior.

    bikini swimsuit How to dress like a lady. This article is for girls and women, young or old, who want to dress in a
    more feminine, ladylike way, and for mothers guiding their daughters on how to dress like a lady.
    You’ve seen them out and about or you may be one of them.
    bikini swimsuit

    dresses sale Make sure the consumers are happy with the product, as well as the seller.

    Find out the difference between clear, blue and black in ground
    solar pool covers and know why that is important.
    Many people measure end to end and forget to include the decking.

    dresses sale

    one piece swimsuits Austen was popular in her own era, though she made little money from her writing and remarkably, the
    novels have garnered new fans in the late 20th and 21st centuries and have been dramatised many times for film
    and television. It was a period of social and
    political upheaval, culturally rich but somewhat unstable.
    The French revolution of 1798 99 had made the status quo in England seem
    less secure.. one piece swimsuits

    cheap swimwear It the most entitled thing I can possibly imagine.
    Similar to when a woman wants you to do a thing for her, but she doesn want to have to tell you what it is, because that less magical somehow.
    I get it. It has been a while since people have seen you so you can start off with a fresh, different look without getting all the “are you sick?” comments.
    Get a wash and go hairstyle. Try to create a deicison free wardrobe by
    developing a “uniform.” My uniform is dark pants, black or
    white top, blazer, black shoes cheap swimwear.

  11. 06/01/2020 à 06:57 | #11

    Cheap Flight Deals to Anywhere in the USA. Get great deals with attractive offers only on https://www.pinfare.com .

  1. 25/06/2010 à 15:22 | #1
  2. 01/07/2010 à 10:55 | #2
  3. 03/08/2010 à 14:50 | #3
  4. 21/02/2011 à 10:46 | #4
  5. 05/12/2011 à 13:09 | #5
  6. 15/05/2015 à 07:58 | #6
  7. 26/05/2015 à 00:58 | #7
  8. 01/07/2015 à 23:08 | #8
  9. 02/07/2015 à 01:36 | #9
  10. 06/08/2015 à 17:51 | #10
  11. 11/08/2015 à 01:09 | #11
  12. 02/09/2015 à 23:30 | #12
  13. 03/09/2015 à 08:11 | #13
  14. 03/09/2015 à 11:15 | #14
  15. 04/10/2015 à 17:33 | #15
  16. 30/10/2015 à 20:17 | #16
  17. 16/11/2019 à 16:44 | #17