• ahhhhh (unregistered) in reply to MindChild
    MindChild:
    markfiend:
    A former colleague was fond of if($boolean == TRUE) ...

    I do the same and it has a purpose. I read "If $boolean is equal to true then...". Without that I read "if $boolean..." ... if boolean WHAT?

    Name your booleans better
  • Anonymous Paranoiac (unregistered) in reply to Valued Service
    Valued Service:
    Just a name:
    Well, knowing that $boolean does not eally needs to be holding a boolean (the infamous 'True, false or File_not_found' joke comes to mind) I guess it would not bea too bad an idea to explicitily name it. But than, as other posters here already remarked, when using PHP rather with the type-safe comparision ("===").

    Especially if many people will be editing/adding to that code ...

    ... or ofcourse use a strong-typed language, and raising a red flag when a non-boolean is used where one is expected

    Then, when would you ever not use "==="? When you need to know if "Dog" is equivalent to 23?

    Using type-safe comparisons in weakly typed languages should be standard convention by now.

  • (cs) in reply to faoileag
    faoileag:
    What, you didn't show him the merits of writing a specialized method "isTrue(boolean)"?
    function isNotTrueOrFalse(boolean val)
    {
       return false;
    }
    
  • Anonymous (unregistered) in reply to Arkady
    Arkady:
    My C++ compiler throws a warning if a switch statement has no default case, even if the default case is impossible to hit (e.g. the input is an enum and every possible case is covered.)

    Maybe the coder wants their code to run without warnings?

    C++ does not constrain the values that can be assigned to an enum variable.
    enum Foo { ZERO, ONE, TWO };
    Foo foo = static_cast<Foo>(1337);

  • chris (unregistered) in reply to Anonymous
    Anonymous:
    Arkady:
    My C++ compiler throws a warning if a switch statement has no default case, even if the default case is impossible to hit (e.g. the input is an enum and every possible case is covered.)

    Maybe the coder wants their code to run without warnings?

    C++ does not constrain the values that can be assigned to an enum variable.
    enum Foo { ZERO, ONE, TWO };
    Foo foo = static_cast<Foo>(1337);
    I was about to ask whether C++ compilers didn't allow you to suppress specific warnings by ID?

    From reading Anonymous's answer in the meantime, maybe not such a good idea...

  • Niels E. Rasmussen (unregistered) in reply to gramie
    gramie:
    MindChild:
    I do the same and it has a purpose. I read "If $boolean is equal to true then...". Without that I read "if $boolean..." ... if boolean WHAT?

    In that case, why don't you name your Boolean variable to something useful, like $userIsAdmin or $TransactionCompleted? Then the code reads:

    "if $userIsAdmin"

    and it makes sense.

    Thank you! Finally some sense!

  • bperkins (unregistered)

    What does "ternary" have to do with ponies and rainbows?

  • Coward (unregistered) in reply to MiniMax
    MiniMax:
    A snippet from a piece of Java code in "my" system:

    Boolean lbBusinessEbox = Boolean.TRUE; ... if (lxUserInfo.getBusinessFlag().equals(Boolean.FALSE)) lbBusinessEbox = Boolean.FALSE;

    It took me several passes and a quick consulting by a friend to make I sure I really understood what was going on.

    not quite as good as the one I saw the other day in our codebase

    Map<String,Boolean> myMap = new HashMap<String,Boolean>(300);

    SNIP

    Boolean bool = myMap.get("a string"); if(bool != null && bool.equals(Boolean.TRUE))

  • emaNrouY-Here (unregistered)

    case (if ( first == post ? true : false) {true;}{false;}) { true: break; false: break; default: FILE_NOT_FOUND }

    Wow. I'm sure I've tried to do something like this (after a case, create a new if statement to handle the next condition) until I realized I should just call a new function for that. But that was while I was learning to code, not in an actual project.

  • d.k.ALlen (unregistered)

    I prefer to simply say: if ( some_bool_expr ) {}

    However, if I am in the middle of code generated by unix-weenies who have brought their thrice-cursed scripting skillz over to c/c++ (which happens frequently), I explicitly do:

    if ( some_bool_expr == true ) {}

    because the existing code will be littered with:

    return 0; // meaning, success, which is brain-dead stupid

    and the following corresponding wonderful bits:

    if ( some_stupid_function() ) { error_handling_code }

    I guess the real WTF is allowing anyone who returns 0 for success, anywhere near a real compiler.

    (/over-the-top-pet-peeve-posting)

  • anonymous (unregistered)

    Wow. I'm surprised with all the utterly amazing coders here that nobody seems to understand the concept of future-proofing your code.

    You are typically one of many maintainers. You are typically not the last maintainer. Always having a default case in a switch statement, even if it is impossible when you write the code, allows you to log an error if someone else changes something that makes it possible.

    For example, if you have an enum where all the cases are covered (as mentioned earlier) and somebody who is unaware of the particular switch statement you wrote adds a new value to the enum but doesn't extend the switch statement, then you typically want it to result in an error message. Ignoring this possibility makes it easier to introduce bugs. Take, for example, the following pseudocode:

    foo.h-ish:

    enum WORD { fizz=0, buzz, bang };
    

    bar.pseudoc:

    ...
    WORD w = ...;
    int i;
    switch(w) {
      case fizz: i=0; break;
      case buzz: i=5; break;
      case bang: i=17; break
    }
    ...
    

    If Sum Dum Guoy adds "thwomp" to WORD, but doesn't modify the switch, then i will be undefined. This is typically A Bad Thing(tm). If there were a default case that generated an error, then testing could catch what the developer did not.

    Ah, but I forget, everyone who visits TDWTF writes perfect code, and works in shops where everyone writes perfect code, and only perfect coders are hired, so this could never happen in your world.

  • Edmund (unregistered) in reply to markfiend

    That's not so terrible. Some languages don't have boolean type and you soon learn to distrust the boolean interpretation of constants if you're developing on multi-platforms.

  • (cs)

    The truth? You can't handle the truth!

    You must only handle 1, 2 and FILE_NOT_FOUND.

  • Coward (unregistered) in reply to anonymous
    anonymous:
    Wow. I'm surprised with all the utterly amazing coders here that nobody seems to understand the concept of future-proofing your code.

    You are typically one of many maintainers. You are typically not the last maintainer. Always having a default case in a switch statement, even if it is impossible when you write the code, allows you to log an error if someone else changes something that makes it possible.

    For example, if you have an enum where all the cases are covered (as mentioned earlier) and somebody who is unaware of the particular switch statement you wrote adds a new value to the enum but doesn't extend the switch statement, then you typically want it to result in an error message. Ignoring this possibility makes it easier to introduce bugs. Take, for example, the following pseudocode:

    foo.h-ish:

    enum WORD { fizz=0, buzz, bang };
    

    bar.pseudoc:

    ...
    WORD w = ...;
    int i;
    switch(w) {
      case fizz: i=0; break;
      case buzz: i=5; break;
      case bang: i=17; break
    }
    ...
    

    If Sum Dum Guoy adds "thwomp" to WORD, but doesn't modify the switch, then i will be undefined. This is typically A Bad Thing(tm). If there were a default case that generated an error, then testing could catch what the developer did not.

    Ah, but I forget, everyone who visits TDWTF writes perfect code, and works in shops where everyone writes perfect code, and only perfect coders are hired, so this could never happen in your world.

    +1 This actually happened the other day. luckily someone put defaults in that threw exceptions and then I stranged the others who didn't

  • Coward (unregistered) in reply to anonymous
    anonymous:
    Wow. I'm surprised with all the utterly amazing coders here that nobody seems to understand the concept of future-proofing your code.

    You are typically one of many maintainers. You are typically not the last maintainer. Always having a default case in a switch statement, even if it is impossible when you write the code, allows you to log an error if someone else changes something that makes it possible.

    For example, if you have an enum where all the cases are covered (as mentioned earlier) and somebody who is unaware of the particular switch statement you wrote adds a new value to the enum but doesn't extend the switch statement, then you typically want it to result in an error message. Ignoring this possibility makes it easier to introduce bugs. Take, for example, the following pseudocode:

    foo.h-ish:

    enum WORD { fizz=0, buzz, bang };
    

    bar.pseudoc:

    ...
    WORD w = ...;
    int i;
    switch(w) {
      case fizz: i=0; break;
      case buzz: i=5; break;
      case bang: i=17; break
    }
    ...
    

    If Sum Dum Guoy adds "thwomp" to WORD, but doesn't modify the switch, then i will be undefined. This is typically A Bad Thing(tm). If there were a default case that generated an error, then testing could catch what the developer did not.

    Ah, but I forget, everyone who visits TDWTF writes perfect code, and works in shops where everyone writes perfect code, and only perfect coders are hired, so this could never happen in your world.

    +1 This actually happened the other day. luckily someone put defaults in that threw exceptions and then I stranged the others who didn't

  • Albert_dH (unregistered) in reply to flop
    flop:
    Arkady:
    My C++ compiler throws a warning if a switch statement has no default case, even if the default case is impossible to hit (e.g. the input is an enum and every possible case is covered.)
    Ever heard of ECC, bit errors, gamma rays, bad RAM, bugs in the CPU, and so on?

    On top of those (rarer) cases try someone extending the enumeration to more values. Then those sane defaults can chop days off of the time to get the app running again.

    Of course insane default clauses will not help at all. And marginally sane ones will cause you to lose hair...

  • Ben Jammin (unregistered) in reply to Lorne Kates
    Lorne Kates:
    faoileag:
    What, you didn't show him the merits of writing a specialized method "isTrue(boolean)"?
    function isNotTrueOrFalse(boolean val)
    {
       return false;
    }
    

    Looks like some premature optimization. Shouldn't that read:

    function isNotTrueOrFalse(boolean val)
    {
       return !(true || false);
    }
    
  • Jazz (unregistered) in reply to Arkady
    Arkady:
    My C++ compiler throws a warning if a switch statement has no default case, even if the default case is impossible to hit (e.g. the input is an enum and every possible case is covered.)

    Maybe the coder wants their code to run without warnings?

    Seriously, C++ compilers are some perfect storm of stupidity and touchiness. At least the warning for no default case is just a warning and is potentially useful. Back in my first year of college we used some compiler -- I think it was Borland -- that would arbitrarily refuse to compile your code if it thought you had the wrong number of comments in it. Yes, comments. Adding or deleting lines that were entirely comments would change whether or not the compiler would (a) work properly, (b) appear to work properly but generate a binary consisting of nothing but segfaults, or (c) simply refuse to compile. And this was a professional-grade compiler, in a setting supervised by CS professors with years of experience, so there is no plausible reason to believe that such behavior was not standard.

    My favorite quote about C++ is that "C++ is not a language, it is a collection of ways to screw up."

    (Captcha: "distineo" -- If you're really evil in this life, your distineo is to use C++ for all eternity.)

  • Jazz (unregistered) in reply to JimLahey
    JimLahey:
    It's still the best PHP I've ever seen, WTFs and all.

    Not that PHP doesn't have lots of warranted criticisms, but if this is the best PHP you've seen you've never worked with anyone who actually knew PHP. Don't let this site be your only example.

  • Will (unregistered) in reply to markfiend
    markfiend:
    A former colleague was fond of if($boolean == TRUE) ...
    Count me as one who use to do that. It for making it easy to read.
  • (cs) in reply to Arkady
    Arkady:
    My C++ compiler throws a warning if a switch statement has no default case, even if the default case is impossible to hit (e.g. the input is an enum and every possible case is covered.)

    Maybe the coder wants their code to run without warnings?

    I do agree that's probably why the end of the world bit. It doesn't explain the switch statement in the first place.

  • gnasher729 (unregistered) in reply to Arkady
    Arkady:
    My C++ compiler throws a warning if a switch statement has no default case, even if the default case is impossible to hit (e.g. the input is an enum and every possible case is covered.)

    Maybe the coder wants their code to run without warnings?

    That's sad. I used a compiler probably 18 years ago that would give you warnings if most, but not all, possible values of an enum were covered - if you covered 5 out of 6 or 117 out of 119, that's most likely a bug (someone added a new enum value).

  • Joe Coder (unregistered) in reply to markfiend

    I prefer the more idiomatic version:

    if(TRUE == $boolean)
  • not Tye (unregistered)

    "return 0; // meaning, success, which is brain-dead stupid"

    While I agree. I understand the reason. There can be only 1 success value, but you may want to return any number of non-success values.

  • Anonymous (unregistered)
    if(my_bool == true)
    { ...
    You should be flogged for doing this. If you can't understand clean, terse code then go flip burgers.
  • jay (unregistered) in reply to markfiend
    markfiend:
    A former colleague was fond of if($boolean == TRUE) ...

    It could be worse. I spent a few years working on a system where the original programmer was found of writing ... this was a Java program:

    if (flag.toString().equals("true"))
    

    I cried.

  • (cs) in reply to Nagesh
    Nagesh:
    No joke about president's daughter yet.

    BTW- margaret thacher is dead. please mourn her for 1 minute.

    "Mourn"? Oh fuck off! I'd be dancing except there's nothing on the fucking radio to dance to, there's been 100% coverage of brown-nose thatcher the fucking snatcher.

  • d.k.ALlen (unregistered) in reply to not Tye
    not Tye:
    "return 0; // meaning, success, which is brain-dead stupid"

    While I agree. I understand the reason. There can be only 1 success value, but you may want to return any number of non-success values.

    Yes, and this is done, well, everywhere. You can use an enum, and I'm okay with that so long as you do: if ( status == SUCCESSFUL ) but that's still conflating two concepts into one variable (which is one of the fundamental mistakes programmers make, which devolves into maintenance and feature-expansion nightmares)...

    Success of an action is one concept. The reason for the failure of an action is a different concept. Because SUCCESS is mutually exclusive with the reason for failure, one usually gets away with this.

    Until someone wants to return a reason for a warning.

    Try: struct Result { bool status; enum FailureReason failureReason; };

    struct Result someFunction();

    It looks messier, but it is significantly more resilient to subsequent enhancements.

    (I've actually seen the following, although I'm paraphrasing for language reasons:)

    struct Result { bool status; std::set<DiagnosticCodes> diagCodes; };

    which allows one to return multiple info, warning, and/or error codes to the caller, which is then able to display much more information to the wayward user.


    But if you MUST conflate success/failure with failure-reason, then always use an enum, and never test-for-zero (or non-zero) on return (instead, test against the enum labels).

  • jay (unregistered) in reply to Anonymous Paranoiac
    Anonymous Paranoiac:
    Valued Service:
    Just a name:
    Well, knowing that $boolean does not eally needs to be holding a boolean (the infamous 'True, false or File_not_found' joke comes to mind) I guess it would not bea too bad an idea to explicitily name it. But than, as other posters here already remarked, when using PHP rather with the type-safe comparision ("===").

    Especially if many people will be editing/adding to that code ...

    ... or ofcourse use a strong-typed language, and raising a red flag when a non-boolean is used where one is expected

    Then, when would you ever not use "==="? When you need to know if "Dog" is equivalent to 23?

    Using type-safe comparisons in weakly typed languages should be standard convention by now.

    Abolishing weakly-typed languages should be a standard convention by now.

    It baffles me why some people think that having a variable that might contain an integer or might contain a string is a good idea. For the rare cases where this is a useful feature, fine, have some sort of generic Object data type.

  • d.k.ALlen (unregistered) in reply to d.k.ALlen
    d.k.ALlen:
    But if you MUST conflate success/failure with failure-reason, then *always* use an enum, and *never* test-for-zero (or non-zero) on return (instead, test against the enum labels).

    Presuming, of course, that your language supports enums. If not, use constants.

  • jay (unregistered) in reply to anonymous
    anonymous:
    Wow. I'm surprised with all the utterly amazing coders here that nobody seems to understand the concept of future-proofing your code.

    You are typically one of many maintainers. You are typically not the last maintainer. Always having a default case in a switch statement, even if it is impossible when you write the code, allows you to log an error if someone else changes something that makes it possible.

    For example, if you have an enum where all the cases are covered (as mentioned earlier) and somebody who is unaware of the particular switch statement you wrote adds a new value to the enum but doesn't extend the switch statement, then you typically want it to result in an error message. Ignoring this possibility makes it easier to introduce bugs. Take, for example, the following pseudocode:

    foo.h-ish:

    enum WORD { fizz=0, buzz, bang };
    

    bar.pseudoc:

    ...
    WORD w = ...;
    int i;
    switch(w) {
      case fizz: i=0; break;
      case buzz: i=5; break;
      case bang: i=17; break
    }
    ...
    

    If Sum Dum Guoy adds "thwomp" to WORD, but doesn't modify the switch, then i will be undefined. This is typically A Bad Thing(tm). If there were a default case that generated an error, then testing could catch what the developer did not.

    Ah, but I forget, everyone who visits TDWTF writes perfect code, and works in shops where everyone writes perfect code, and only perfect coders are hired, so this could never happen in your world.

    If we're talking about a switch statement to handle all the possible values of an enum (or something that should have been an enum if the programmer had been smarter and/or the language had enums), then yes, I agree, it makes very good sense to have a default case that that calls PanicAbortWeAreGoingDown(). Just in case you forgot one or someone in the future adds another case.

    But in this case, he's testing for equality, there are only two possibilities: the things be the same or the be not the same. There's not much need for a default case. It should be a simple if/else. If someone adds a third possibility (FILE_NOT_FOUND or whatever), then they need to restructure the block, because they're doing something fundamentally different than what was done before.

  • Anonymous Paranoiac (unregistered) in reply to jay
    jay:
    Anonymous Paranoiac:

    Using type-safe comparisons in weakly typed languages should be standard convention by now.

    Abolishing weakly-typed languages should be a standard convention by now.

    It baffles me why some people think that having a variable that might contain an integer or might contain a string is a good idea. For the rare cases where this is a useful feature, fine, have some sort of generic Object data type.

    Oh, I completely agree. Weakly-typed languages are an abomination. Unfortunately, we're effectively stuck with them, at least if you do web programming (you may be able to avoid PHP, but you're kind of stuck with JS).

    CAPTCHA: iusto - When I was a newb, iusto like weakly typed languages. Then I learned better.

  • n_slash_a (unregistered) in reply to faoileag
    faoileag:
    EuroGuy:
    flop:
    Ever heard of ECC, bit errors, gamma rays, bad RAM, bugs in the CPU, and so on?
    If every conditional statement in your code covers for the possibility of bad RAM, I don't want to see your code - ever.
    Not every. You only need to do this with switch-statements. And yes, with switch-statements, a default branch is a sensible thing to have. Some coding styles even mandate them :-)
    I work the in the GPS field for airplanes, if you are in an airplane on final approach, I bet you would like to know that an accidental bit flip condition is covered defensively and not have the airplane think it is suddenly at 1000 feet when it is really at 100 feet.
  • drake (unregistered) in reply to n_slash_a
    n_slash_a:
    faoileag:
    EuroGuy:
    flop:
    Ever heard of ECC, bit errors, gamma rays, bad RAM, bugs in the CPU, and so on?
    If every conditional statement in your code covers for the possibility of bad RAM, I don't want to see your code - ever.
    Not every. You only need to do this with switch-statements. And yes, with switch-statements, a default branch is a sensible thing to have. Some coding styles even mandate them :-)
    I work the in the GPS field for airplanes, if you are in an airplane on final approach, I bet you would like to know that an accidental bit flip condition is covered defensively and not have the airplane think it is suddenly at 1000 feet when it is really at 100 feet.

    1000 to 100 looks like two bit flips to me, but that still is only a difference of 4 feet - are GPS systems any more accurate than that?

  • Joe Heyming (unregistered)

    Reminds me of this:

    if (some_boolean_statement) { // do nothing } else { actual_implementation(); }

    why not this: if (!some_boolean_statement) { actual_implementation(); }

  • Mar - hey is that a butterfly? (unregistered)

    The first dwtf in a while that wasn't plagued by incessant useless dramatization. Yes, even our codesods seem to require long and laborious back stories now. Glad this one was short and to the point. My ADHD can't handle the way dwtf stories have been trending. That tree outside my window sure looks neat.

  • mophobiac (unregistered)

    Lazy. Should have inline assembler to HCF

  • Tim (unregistered)

    One of my coworkers likes to invert conditionals like this:

    if(isLoggedIn) { } // Purposely left empty else { GoDoSomething(); }

    I'm worried it may be too late to teach him about '!' and '!='.

  • JJ (unregistered) in reply to Joe Coder
    Joe Coder:
    I prefer the more idiomatic version:
    if(TRUE == $boolean)
    Argh. Say no to Yoda code.
  • (cs) in reply to just me
    just me:
    markfiend:
    A former colleague was fond of if($boolean == TRUE) ...

    Very useful pattern in C, in conjunction with:

    #define TRUE 0 #define FALSE 1

    We used to do this (or the equivalent) in every PL/1 program, plus:

    #define NO 0 #define YES 1 #define OFF 0 #define ON 1 #define NO_ERROR 0 #define DOOMSDAY 0

    That last one was for the benefit of loops that were supposed to continue indefinitely, ending only when some external force shut down the program they appeared in, so:

    do until (DOOMSDAY)

  • RFoxmich (unregistered)

    This is php TRWTF given the possiblity of crafted posts and non string valued posts is that this was not written:

    switch( $_POST["operation"] ) { case 'editUser':// editUser // SNIP break; case 'saveUser'://saveUser // SNIP break; default://endOfTheWorld debug( "You no can fool me with crafted posts." ); break;
    }

  • TheCPUWizard (unregistered) in reply to Arkady
    Arkady:
    My C++ compiler throws a warning if a switch statement has no default case, even if the default case is impossible to hit (e.g. the input is an enum and every possible case is covered.)

    Maybe the coder wants their code to run without warnings?

    DEspise what you may think, and enum (in C++) is still just an integer and is NOT constrained to the defined values...you NEED a default case!

  • (cs) in reply to jay
    jay:
    markfiend:
    A former colleague was fond of if($boolean == TRUE) ...

    It could be worse. I spent a few years working on a system where the original programmer was found of writing ... this was a Java program:

    if (flag.toString().equals("true"))
    

    I cried.

    I think bash.org has this one:

    if(b.toString().toLower().substring(0, 1) == "t") {
    

    Also, I like this:

    switch(enumValue) {
       case enum.whatever:
          doSomething();
          break;
       case enum.whatever2:
          doSomething2();
          break;
       case enum.whatever3:
          doSomething3();
          break;
       default:
          throw new InvalidEnumArgumentException("helpful message");
    }
    
  • Henry Troup (unregistered) in reply to markfiend
    markfiend:
    A former colleague was fond of if($boolean == TRUE) ...

    Thorough paranoia requires

     if (TRUE == $boolean )...

    Just in case one = is omitted.

    After all, if you're going to step away from the compilers test, you have to guard against doing it wrong.

    (CAPTCHA: Usitas, like gravitas, the appearance of usability without the reality. )

  • Norman Diamond (unregistered) in reply to Lorne Kates
    Lorne Kates:
    faoileag:
    What, you didn't show him the merits of writing a specialized method "isTrue(boolean)"?
    function isNotTrueOrFalse(boolean val)
    {
       return false;
    }
    
    WhereTF did you find that? I know WhereTF you didn't find that file.
  • Norman Diamond (unregistered) in reply to da Doctah
    da Doctah:
    just me:
    markfiend:
    A former colleague was fond of if($boolean == TRUE) ...
    Very useful pattern in C, in conjunction with: #define TRUE 0 #define FALSE 1
    We used to do this (or the equivalent) in every PL/1 program, plus: #define NO 0 #define YES 1 #define OFF 0 #define ON 1 #define NO_ERROR 0 #define DOOMSDAY 0
    Brillant. I was about to ask about the inconsistency between TRUE and NO, and between FALSE and ON, etc. But then I figured out you did that intentionally, because unmaintainability == job security.
  • Bill C. (unregistered) in reply to Valued Service
    Valued Service:
    IsUserAvailable is a boolean.

    IsUserAvailableNullable is a nullable boolean.

    UserAvailability is an enum. (AvailableWeekdays, AvailableWeekends, AvailableAfterHours).

    UserAvailabilityFlags is an enum with flag attribute set.

    We need a bitmask, because she was available weekdays, weekends, and after hours ... and she knew how to raise a flag, too. I wish I'd known how to make her nullable.

  • Cheong (unregistered)

    Once upon a time, we have code sanity checker that insist every switch clock must have "default" branching, so it added another level of insanity to our code.

  • Petersz (unregistered)

    As we all know the correct solution would have been:

    switch( $_POST["operation"] == "editUser" ? "editUser" : "saveUser" ) {
          case "editUser": // editUser
            // SNIP
            break;
          case "saveUser": // saveUser
            // SNIP
            break;
          case "endOfTheUniverseAndAll": // endOfTheUniverseAndAll
            // SNIP
            break;
          default: //endOfTheWorld
            debug( "endOfTheWorld" );
            break;  
       }
    
  • Meep (unregistered) in reply to anonymous
    anonymous:
    Wow. I'm surprised with all the utterly amazing coders here that nobody seems to understand the concept of future-proofing your code.

    You are typically one of many maintainers. You are typically not the last maintainer. Always having a default case in a switch statement, even if it is impossible when you write the code, allows you to log an error if someone else changes something that makes it possible.

    For example, if you have an enum where all the cases are covered (as mentioned earlier) and somebody who is unaware of the particular switch statement you wrote adds a new value to the enum but doesn't extend the switch statement, then you typically want it to result in an error message. Ignoring this possibility makes it easier to introduce bugs.

    No, you'll still get a bug, it's just that it's going to fail sooner. Hopefully.

    What you need is a unit test that automatically feeds all possible values of that enum. Or you need to encapsulate that logic in a class, so the enum is only used in a few predictable places.

    But since you're all programming in a nice, shiny object oriented language, you rarely use switch statements and enums, right? Because that's what polymorphism and inheritance are for.

Leave a comment on “Switching It Up at the End of the World”

Log In or post as a guest

Replying to comment #:

« Return to Article