Ternary Over a New Leaf

  • TheIrritainer 2013-07-03 07:40
    $isFrist = 0;
    $isFrist = (is_null($isFrist)) ? 0 : $isFrist;
  • eVil 2013-07-03 07:52
    No, it can't be sung to Rule Britannia... it fits neither the verse or chorus structure. You can try to jam loads of syllables into a single note, but it doesn't scan very successfully.

    Heaven's command, by the way... heaven's command, matchless beauty, envy of them all... and don't any of you forget that.
  • Mark Bowytz 2013-07-03 07:55
    Depends on how you choose to pronounce the symbols, or if you choose to. It also can fit to "Happy Birthday" and "Les Petits Reins" if you're creative.
  • Crash 2013-07-03 07:58
    I almost got it to work with "row, row, row your boat".
  • eVil 2013-07-03 08:03
    Mark Bowytz:
    Depends on how you choose to pronounce the symbols, or if you choose to. It also can fit to "Happy Birthday" and "Les Petits Reins" if you're creative.


    Well, you can fit the word "Blah" to The Modern Major General Song if you really want to, but you can't reasonably say that "it fits". Its just words badly fit to some random tune.

    Just singing a melody with X notes, and sentence with Y syllables (Y!=X), in any old haphazard fashion, doesn't mean it scans.
  • GD 2013-07-03 08:06
    initialTab = 0;
    if (isNaN(initialTab)) { initialTab = 0; }

    This is the Butterfly Effect pattern.
    Something might maybe have the possibility of having the probability to cause initialTab to change.
  • Mike 2013-07-03 08:07
    initialTab = 0;
    if (isNaN(initialTab)) { initialTab = 0; }

    Probably best to check that initialTab is a number after that conditional assignment. After all, if the first assignment could fail...
  • Heisenberg 2013-07-03 08:13
    GD:
    initialTab = 0;
    if (isNaN(initialTab)) { initialTab = 0; }

    This is the Butterfly Effect pattern.
    Something might maybe have the possibility of having the probability to cause initialTab to change.


    I really like this quantum-indetermination safe code.
    The variable won't have its value determined until the moment when its value is actually observed.
  • JimLahey 2013-07-03 08:24
    I think me and Jeremy have worked at the same place. The guru there would always quote "belt, braces and superglue" when I asked him about his massive WTFs.
  • Ramchandra Apte 2013-07-03 08:26
    easter egg: click anywhere in "shell-shocked", and surprise!
  • Warren 2013-07-03 08:29
    I was slightly surprised when reading the one about Jeremy's ex-coworker.

    Bear in mind that in "British English" (i.e. English not American) suspenders are called braces.

    Suspenders are lingerie and imply a belt already!

    Of course, this conjures up a totally different image depending on whether you've assumed the coworker is male or female.
  • ZoomST 2013-07-03 08:47
    Warren:
    I was slightly surprised when reading the one about Jeremy's ex-coworker.

    Bear in mind that in "British English" (i.e. English not American) suspenders are called braces.

    Suspenders are lingerie and imply a belt already!

    Of course, this conjures up a totally different image depending on whether you've assumed the coworker is male or female.

    If it is a male coworker, you can try to sing the code as any of "The Rocky Horror Show" songs. Seems legit to me.
  • A 2013-07-03 08:51
    Yes, they really should have been more careful and gone for something like:

    initialTab = 0;
    while (isNaN(initialTab)) { initialTab = 0; }
  • Nutster 2013-07-03 08:54
    Nested if statements: Easy to read, easy to follow the logic, easy to modify the logic if needed.
    Nested Ternary operations: Pain in the brain (way above neck) to read, easy to screw up the logic entirely by misplacing a bracket. Reminds me why I don't write code in LISP anymore.
  • Jim 2013-07-03 08:54
    How terribly unsafe. Better to do:

    initialTab = 0;
    while(isNaN(initialTab)){
    initialTab = 0;
    }
  • Nutster 2013-07-03 09:01
    initialTab = 0;
    
    if (isNaN(initialTab)) { initialTab = 0; }

    Is this what you have to do if you declare a floating-point variable to be volatile? Does it really need to be declared volatile? Let the optimizer do its job.
  • Krunt 2013-07-03 09:12
    Mark Bowytz:
    Depends on how you choose to pronounce the symbols, or if you choose to. It also can fit to "Happy Birthday" and "Les Petits Reins" if you're creative.


    Or literally any Ludacris "song".
  • ¯\(°_o)/¯ I DUNNO LOL 2013-07-03 09:17
    When your only tool is a shell_exec, every problem looks like a shell command.

    And when your only tool is PHP, every problem looks like an opportunity to shoot yourself in the foot.
  • gnasher729 2013-07-03 09:21
    Nutster:
    Nested if statements: Easy to read, easy to follow the logic, easy to modify the logic if needed.
    Nested Ternary operations: Pain in the brain (way above neck) to read, easy to screw up the logic entirely by misplacing a bracket. Reminds me why I don't write code in LISP anymore.


    No difference really to ?: ?: can be harder to read _per line_, but you need fewer lines. Of course in this example, there was no need at all for nesting, if the "not editable" case had been handled first. And putting the source code into some structured form helps with readability.
  • Chaarmann 2013-07-03 09:29
    initialTab = 0;
    if (isNaN(initialTab)) { initialTab = 0; }

    It makes sense if
    - there are concurrent threads accessing and changing the variable and the variable is global (and volatile)
    - the first assignment value is not the character zero, but a capital letter "oh". And O for example then is the abbreviated name for an instance of class "Object".
  • dkf 2013-07-03 09:34
    Nutster:
    initialTab = 0;
    
    if (isNaN(initialTab)) { initialTab = 0; }

    Is this what you have to do if you declare a floating-point variable to be volatile? Does it really need to be declared volatile? Let the optimizer do its job.
    Why have I got this horrible premonition that initialTab is an integer?
  • Anonymous Paranoiac 2013-07-03 09:42
    Chaarmann:
    initialTab = 0;
    if (isNaN(initialTab)) { initialTab = 0; }

    It makes sense if
    - there are concurrent threads accessing and changing the variable and the variable is global (and volatile)


    Unless, of course, the code in question was written in JavaScript, in which case, it's just stupid.
  • golddog 2013-07-03 09:46
    gnasher729:
    Nutster:
    Nested if statements: Easy to read, easy to follow the logic, easy to modify the logic if needed.
    Nested Ternary operations: Pain in the brain (way above neck) to read, easy to screw up the logic entirely by misplacing a bracket. Reminds me why I don't write code in LISP anymore.


    No difference really to ?: ?: can be harder to read _per line_, but you need fewer lines. Of course in this example, there was no need at all for nesting, if the "not editable" case had been handled first. And putting the source code into some structured form helps with readability.


    Fewer lines not a goal. Maintainability is.

    That said, it's a case-by-case basis. I've used nested ternary when it's a simple case and was still easy to read.

    Just try to review your code from the perspective of an outsider: is it something the functionality of which can be gleaned relatively quickly and properly? If not, go to the more verbose if-then-else construct.
  • meh 2013-07-03 09:52
    Chaarmann:
    initialTab = 0;
    if (isNaN(initialTab)) { initialTab = 0; }

    It makes sense if
    - there are concurrent threads accessing and changing the variable and the variable is global (and volatile)


    No, it doesn't. `volatile` is not a substitute for synchronization.
  • The Great Lobachevsky 2013-07-03 10:00
    eVil:
    Well, you can fit the word "Blah" to The Modern Major General Song if you really want to, but you can't reasonably say that "it fits". Its just words badly fit to some random tune.


    I prefer The Elements set to that tune, myself...

    theeeeresss antimony, arsenic, aluminum, selenium...
  • Lehrer was here. 2013-07-03 10:23
    The Great Lobachevsky:
    eVil:
    Well, you can fit the word "Blah" to The Modern Major General Song if you really want to, but you can't reasonably say that "it fits". Its just words badly fit to some random tune.


    I prefer The Elements set to that tune, myself...

    theeeeresss antimony, arsenic, aluminum, selenium...


    And hydrogen and oxygen and nitrogen and rhenium,
    And nickel, neodymium, neptunium, germanium,
    And iron, americium, ruthenium, uranium,
    Europium, zirconium, lutetium, vanadium,
    And lanthanum and osmium and astatine and radium,
    And gold and protactinium and indium and gallium,
    <gasp>
    And iodine and thorium and thulium and thallium.

    There's yttrium, ytterbium, actinium, rubidium,
    And boron, gadolinium, niobium, iridium,
    And strontium and silicon and silver and samarium,
    And bismuth, bromine, lithium, beryllium, and barium.

    There's holmium and helium and hafnium and erbium,
    And phosphorus and francium and fluorine and terbium,
    And manganese and mercury, molybdenum, magnesium,
    Dysprosium and scandium and cerium and cesium.
    And lead, praseodymium, and platinum, plutonium,
    Palladium, promethium, potassium, polonium,
    And tantalum, technetium, titanium, tellurium,
    <gasp>
    And cadmium and calcium and chromium and curium.

    There's sulfur, californium, and fermium, berkelium,
    And also mendelevium, einsteinium, nobelium,
    And argon, krypton, neon, radon, xenon, zinc, and rhodium,
    And chlorine, carbon, cobalt, copper, tungsten, tin, and sodium....
  • eViLegion 2013-07-03 10:24
    The Great Lobachevsky:
    eVil:
    Well, you can fit the word "Blah" to The Modern Major General Song if you really want to, but you can't reasonably say that "it fits". Its just words badly fit to some random tune.


    I prefer The Elements set to that tune, myself...

    theeeeresss antimony, arsenic, aluminum, selenium...


    Yeah but that works, because Mr. Lehrer sat down and figured it out properly..... and hydrogen and oxygen and nitrogen and rhenium... and now look what you've made me do.

    Edit: I bet the guy above didn't type that from memory.
  • Anomaly 2013-07-03 10:25
    The Great Lobachevsky:
    eVil:
    Well, you can fit the word "Blah" to The Modern Major General Song if you really want to, but you can't reasonably say that "it fits". Its just words badly fit to some random tune.


    I prefer The Elements set to that tune, myself...

    theeeeresss antimony, arsenic, aluminum, selenium...


    I prefer the tune to "I am the very model of a Scientist Salarian." Or for the slightly older crowd who remembers Reboot. "Everything is alphanumeric."
  • Ken B 2013-07-03 10:27
    golddog:
    (Nested ternary "?:" operator.)
    Fewer lines not a goal. Maintainability is.

    That said, it's a case-by-case basis. I've used nested ternary when it's a simple case and was still easy to read.

    Just try to review your code from the perspective of an outsider: is it something the functionality of which can be gleaned relatively quickly and properly? If not, go to the more verbose if-then-else construct.
    I have been known to occasionally use a nested "?:" operator. However, they are few and far between in my code, and I always use multiple lines and "proper" indentation to make it more human-readable. For example:
    ( condition_1 )
    
    ? ( ( condition_2 )
    ? value_1
    : value_2
    )
    : ( ( condition_3 )
    ? value_3
    : value_4
    )
    (I sure hope I didn't make a typo in that.)
  • DCRoss 2013-07-03 10:29
    The Great Lobachevsky:
    eVil:
    Well, you can fit the word "Blah" to The Modern Major General Song if you really want to, but you can't reasonably say that "it fits". Its just words badly fit to some random tune.


    I prefer The Elements set to that tune, myself...

    theeeeresss antimony, arsenic, aluminum, selenium...


    Algeria Bulgaria Cambodia Dominica Egypt France the Gambia!
    Aitch-teem-ell, zero. Japan Kazakhstan, Lybia Emm-el, HTML!
    Norway, Oman, Shell exec, Qatar Russia mysql
    Turkey Uruguay Vietnam. Handle the error! Yemen Zimbabwe!
  • eViLegion 2013-07-03 10:43
    DCRoss:

    Algeria Bulgaria Cambodia Dominica Egypt France the Gambia!
    Aitch-teem-ell, zero. Japan Kazakhstan, Lybia Emm-el, HTML!
    Norway, Oman, Shell exec, Qatar Russia mysql
    Turkey Uruguay Vietnam. Handle the error! Yemen Zimbabwe!


    Did you just have a stroke in your superior temporal gyrus?
  • DCRoss 2013-07-03 10:45
    eViLegion:

    Did you just have a stroke in your superior temporal gyrus?


    Perhaps singing code out loud is not a thread-safe operation.
  • eViLegion 2013-07-03 10:47
    DCRoss:
    eViLegion:

    Did you just have a stroke in your superior temporal gyrus?


    Perhaps singing code out loud is not a thread-safe operation.


    So, definitely a stroke then.
  • Steve The Cynic 2013-07-03 11:17
    Mark Bowytz:
    Depends on how you choose to pronounce the symbols, or if you choose to. It also can fit to "Happy Birthday" and "Les Petits Reins" if you're creative.

    This reference confuses me. I keep trying to read it as "The little kidneys" - although this word "kidney" requires care when translating between English and French, as the sort of kidney you eat (non-cannibalistically!) is not a "rein" but a "rognon". The ones in the rear part of your abdomen are "reins", and they are "reins" while still inside a living animal, changing to "rognons" when they are removed and used for culinary purposes.
  • Lehrer was here. 2013-07-03 11:18
    eViLegion:
    Edit: I bet the guy above didn't type that from memory.


    Yah, I had to look up the rest of the lyrics...

    I can still recite "Mother", "Pigeons", and "Irish Ballad" from memory though (much to the dismay of those around me...)
  • Hotline for ternary abuse 2013-07-03 11:25
    Let's see if formatting that ternary makes it any clearer...
    (pffftt...!)

    return (isEdited() ? ((!usePercentage()) ? editedFixedAmount
    
    : ((percentageOfBasis == null) ? NullMoney.NULL_AMOUNT
    : basis.multiply(percentageOfBasis)))
    : NullMoney.NULL_AMOUNT);


    Nope, no luck. The author of this pile of shite should be sentenced to debugging and modifying this pile of code excrement on a Friday afternoon before a holiday weekend.
  • pscs 2013-07-03 11:28
    golddog:

    Fewer lines not a goal. Maintainability is.


    Ah, but people have coding standards you know! The type of thing that says 'there shall be no more than 20 lines per function'. So, you have to squeeze as much into each line as you can! You can even fit several actions onto a single line if you use commas judiciously, even if your coding standards mandate only on statement per line.
  • Ironside 2013-07-03 11:34
    public Money getFinanceCredit() {
    return (isEdited() ? ((!usePercentage()) ? editedFixedAmount :
    ((percentageOfBasis == null) ? NullMoney.NULL_AMOUNT :
    basis.multiply(percentageOfBasis))) : NullMoney.NULL_AMOUNT);
    }


    I rewrote it clearer:


    public Money getFinanceCredit()
    {
    if (!isEdited())
    return NullMoney.NULL_AMOUNT;
    if (!usePercentage())
    return editedFixedAmount;
    if (percentageOfBasis == null)
    return NullMoney.NULL_AMOUNT;
    return basis.multiply(percentageOfBasis);
    }


    This still isn't good though. The main problem is that the method is doing too much. It should just return the finance credit, not do validation as well. Validation should be done in a separate method which can be called if necessary.


    public Money getFinanceCredit()
    {
    if (!IsValidState())
    return NullMoney.NULL_AMOUNT;
    if (usePercentage())
    return basis.multiply(percentageOfBasis);
    return editedFixedAmount;
    }

    public bool IsInputValid()
    {
    if (!isEdited())
    return false;
    if (usePercentage() && percentageOfBasis == null)
    return false;
    return true;
    }


    Although there are still more problems such as the need for NullMoney.NULL_AMOUNT at all and the fact percentageOfBasis can equal null (why not have a default?). The naming also is faulty and unclear.

    basis.multiply(percentageOfBasis)

    What does that have to do with finance credit? the term finance credit isn't in the names of those variables at all.

    And NullMoney.NULL_AMOUNT. WTF does that even mean?

    Surely it means something like Money.InvalidState

    But even that is a WTF why not return null?
  • Jeremy 2013-07-03 11:34
    That definitely improves on it, but I personally I still feel it's needlessly complicated. If you're not doing something trivial like
    i%2==0?"Even":"Odd"
    then I have to disagree with a ternary approach. Even a somewhat veteran programmer needs to "process" that way more than should have to considering the appropriate if/else structure could be followed by someone 2 days into programming 101.
  • eViLegion 2013-07-03 11:38
    pscs:
    golddog:

    Fewer lines not a goal. Maintainability is.


    Ah, but people have coding standards you know! The type of thing that says 'there shall be no more than 20 lines per function'. So, you have to squeeze as much into each line as you can! You can even fit several actions onto a single line if you use commas judiciously, even if your coding standards mandate only on statement per line.


    Yeah... maybe you should architect your code to break large functions into a number of smaller, maintainable functions, then you wouldn't have to rely on esoteric language features to smugly get round that shit.
  • Steve The Cynic 2013-07-03 11:44
    Hotline for ternary abuse:
    Let's see if formatting that ternary makes it any clearer...
    (pffftt...!)

    return (isEdited() ? ((!usePercentage()) ? editedFixedAmount
    
    : ((percentageOfBasis == null) ? NullMoney.NULL_AMOUNT
    : basis.multiply(percentageOfBasis)))
    : NullMoney.NULL_AMOUNT);


    Nope, no luck. The author of this pile of shite should be sentenced to debugging and modifying this pile of code excrement on a Friday afternoon before a holiday weekend.

    Rewrite it in if()ese:
    if( isEdited() )
    
    {
    if( !usePercentage() )
    return editedFixedAmount;
    else if( percentageOfBasis == null )
    return NullMoney.NULL_AMOUNT;
    else
    return basis.multiply(percentageOfBasis);
    }
    else
    return NullMoney.NULL_AMOUNT;

    Or alternatively, in English-like:
    If the thingy was edited, then use the percentage times the basis if we are using a percentage and one is available, or if we are not using a percentage, use the fixed amount. If none of the above conditions are met, use the null amount.

    In general, I'd prefer to invert the is-null test so that the positive "use-something" conditions are clumped together, and I'd prefer a function "useFixedAmount()" that is equivalent to "!userPercentage()" so that the test looks more related to the code in the branches, but it's reasonably clear.
    if( isEdited() )
    
    {
    if( useFixedAmount() )
    return editedFixedAmount;
    else if( percentageOfBasis != null )
    return basis.multiply(percentageOfBasis);
    else
    return NullMoney.NULL_AMOUNT;
    }
    else
    return NullMoney.NULL_AMOUNT;

    Better?
  • Jeremy 2013-07-03 11:50
    eViLegion:
    pscs:
    golddog:

    Fewer lines not a goal. Maintainability is.


    Ah, but people have coding standards you know! The type of thing that says 'there shall be no more than 20 lines per function'. So, you have to squeeze as much into each line as you can! You can even fit several actions onto a single line if you use commas judiciously, even if your coding standards mandate only on statement per line.


    Yeah... maybe you should architect your code to break large functions into a number of smaller, maintainable functions, then you wouldn't have to rely on esoteric language features to smugly get round that shit.


    Indeed. I'm not sure I agree with just declaring "no function can be over 20 lines, ever, period." But the point of such a declaration is that a large function is a sign you're doing something else wrong, not an invitation to "collapse" your overdone function into an even crappier version.
  • neminem 2013-07-03 11:56
    Lehrer was here.:
    eViLegion:
    Edit: I bet the guy above didn't type that from memory.


    Yah, I had to look up the rest of the lyrics...

    I can still recite "Mother", "Pigeons", and "Irish Ballad" from memory though (much to the dismay of those around me...)

    I have Oedipus Rex and Bright College Days memorized. And most of Poisoning Pigeons in the Park and Pollution, but I blank on lines sometimes. Only have about a verse of The Elements memorized; that's all you really need.
  • Zylon 2013-07-03 11:56
    JimLahey:
    I think me and Jeremy have worked at the same place. The guru there would always quote "belt, braces and superglue" when I asked him about his massive WTFs.

    A quote is only a quote if it's quoted from something. WTF is "belt, braces and superglue"?
  • not else 2013-07-03 12:24
    So its agreeded then.

    "if not x then without-x else with-x" is a bad pattern.

    Prefer "if x then with-x else without-x".
  • nmare 2013-07-03 12:26
    Ken B:
    I have been known to occasionally use a nested "?:" operator. However, they are few and far between in my code, and I always use multiple lines and "proper" indentation to make it more human-readable. For example:
    ( condition_1 )
    
    ? ( ( condition_2 )
    ? value_1
    : value_2
    )
    : ( ( condition_3 )
    ? value_3
    : value_4
    )
    (I sure hope I didn't make a typo in that.)


    Then why dont you use a good old if() structure? There no adventage to use ternary ops in this case.

    Ternary operator are always horrible to read. The only case where i use it is on SSIS with the conditional split because you can only enter ONE line of code w/o indentation/carriage return. It often give a mess worst then the today's wtf.

    You should kill the inventor of ternary ops!
  • chubertdev 2013-07-03 12:28
    heh


    var isReadable = (isWTF ? getWTF() : (makeReadable() ? getReadable() : FILE_NOT_FOUND));
  • nmare 2013-07-03 12:39
    pscs:
    golddog:

    Fewer lines not a goal. Maintainability is.


    Ah, but people have coding standards you know! The type of thing that says 'there shall be no more than 20 lines per function'. So, you have to squeeze as much into each line as you can! You can even fit several actions onto a single line if you use commas judiciously, even if your coding standards mandate only on statement per line.


    The real coding standars is: Make your code readable!

    using an horrible ternary to save you 3-4 lines of code is worst then make a function with over 20 lines.
  • bob 2013-07-03 13:07
    Multiple returns in a statement? Blasphemy!
  • Niko 2013-07-03 13:08
    TRWTF is, as usual, PHP.

    // on first glance, the following appears to output 'true'
    echo (true?'true':false?'t':'f');

    // however, the actual output of the above is 't'
    // this is because ternary expressions are evaluated from left to right

    // the following is a more obvious version of the same code as above
    echo ((true ? 'true' : false) ? 't' : 'f');

    If anyone working on your codebase has even thought about PHP, ternary operators should be verbotenated.

    (And anyone who nests them should be sucker-punched once for every ? and twice for every : in the expression)
  • doug 2013-07-03 13:10
    initialTab = 0;
    if (isNaN(initialTab)) { initialTab = 0; }

    is probably a merge error.
  • chaosprime 2013-07-03 13:18
    Today's WTF: reading thedailywtf.com talking about the conditional operator as "the ternary operator".

    Any operator that takes three arguments is a ternary operator.
  • nmare 2013-07-03 13:31
    chaosprime:
    Today's WTF: reading thedailywtf.com talking about the conditional operator as "the ternary operator".

    Any operator that takes three arguments is a ternary operator.


    from wikipedia:

    Many programming languages that use C-like syntax feature a ternary operator, ?:, which defines a conditional expression. Since this operator is often the only existing ternary operator in the language, it is sometimes simply referred to as "the ternary operator". In some languages, this operator is referred to as "the conditional operator".


  • eViLegion 2013-07-03 13:40
    chaosprime:
    Today's WTF: reading thedailywtf.com talking about the conditional operator as "the ternary operator".

    Any operator that takes three arguments is a ternary operator.


    We all already know this. But since most commonly used languages only have at most one, then it is THE one.
  • ForFoxSake 2013-07-03 13:55
    I'm always amazed that in most threads you can find brilliant developers and painful idiots but no one in between.
  • da Doctah 2013-07-03 14:07
    DCRoss:
    Algeria Bulgaria Cambodia Dominica Egypt France the Gambia!
    Aitch-teem-ell, zero. Japan Kazakhstan, Lybia Emm-el, HTML!
    Norway, Oman, Shell exec, Qatar Russia mysql
    Turkey Uruguay Vietnam. Handle the error! Yemen Zimbabwe!
    No, no, no, no, no, no! Countries are sung to the tune of the Mexican Hat Dance!
  • eViLegion 2013-07-03 14:09
    ForFoxSake:
    I'm always amazed that in most threads you can find brilliant developers and painful idiots but no one in between.


    Well, I just found you to be thoroughly mediocre. Glad I could help.
  • jay 2013-07-03 14:21
    chaosprime:
    Today's WTF: reading thedailywtf.com talking about the conditional operator as "the ternary operator".

    Any operator that takes three arguments is a ternary operator.


    Any prime number that is divisible by 2 is an "even prime". However, I don't think it creates a great deal of ambiguity to talk about "the even prime", because there is only one.
  • jay 2013-07-03 14:35
    My humble opinion on the "?:" operator (I'll avoid calling it the ternary operator so I don't offend an earlier poster):

    It's handy when you would otherwise have had to declare a temporary variable, for example, if you are passing a value to a function:


    processAccount(acctNum, balance<0 || monthTxCount>20 ? State.WATCH : State.NORMAL);


    Also if it allows you to combine a declaration with an assignment:


    AcctState acctState=balance<0 || monthTxCount>20 ? State.WATCH : State.NORMAL;


    Sure, I could have declared the variable and then had an IF statement to assign the value, but that would turn one line into five.

    And/or if the destination involves a complex expression:


    getCustomer(acctNumber).acctState[periodEnd+1)=balance<0 || monthTxCount>20 ? State.WATCH : State.NORMAL;


    Sure, I could do that one with an IF, but then both ends of the IF would have to repeat that whole complex expression describing where the value goes, which means that a reader would have to stop and figure out that the expressions are the same in both cases. (And of course, sooner or later someone would come along and change one but not realize he needs to also change the other.)

    I avoid using it when any of the three expressions pass a certain threshold of complexity, because then it just gets hard to read.

    I never, ever nest them. That's hard to read.

    And the absolute worst use of a ?: I've ever seen -- stumbled across this one a couple of months ago:


    boolean status = getStatus() ? true : false;


  • jay 2013-07-03 14:38
    chaosprime:
    Today's WTF: reading thedailywtf.com talking about the conditional operator as "the ternary operator".

    Any operator that takes three arguments is a ternary operator.


    We call the receptionist at our company the "unary operator". Because when she forwards a phone call to you, if you give her more than one argument, she just hangs up on you.
  • jay 2013-07-03 14:40
    ¯\(°_o)/¯ I DUNNO LOL:
    When your only tool is a shell_exec, every problem looks like a shell command.

    And when your only tool is PHP, every problem looks like an opportunity to shoot yourself in the foot.


    When your only tool is PHP, you soon want to shoot yourself in the head.
  • chubertdev 2013-07-03 14:47
    da Doctah:
    DCRoss:
    Algeria Bulgaria Cambodia Dominica Egypt France the Gambia!
    Aitch-teem-ell, zero. Japan Kazakhstan, Lybia Emm-el, HTML!
    Norway, Oman, Shell exec, Qatar Russia mysql
    Turkey Uruguay Vietnam. Handle the error! Yemen Zimbabwe!
    No, no, no, no, no, no! Countries are sung to the tune of the Mexican Hat Dance!


    Second time I've posted this on this site:



    United States, Canada, Mexico, Panama...
  • epv 2013-07-03 15:27
    Why not just use if/else statements? There is nothing wrong with them. Just because it compiles doesn't make it a good idea.
  • Hotline for ternary abuse 2013-07-03 15:39
    jay:
    My humble opinion on the "?:" operator (I'll avoid calling it the ternary operator so I don't offend an earlier poster):

    It's handy when you would otherwise have had to declare a temporary variable, for example, if you are passing a value to a function:


    processAccount(acctNum, balance<0 || monthTxCount>20 ? State.WATCH : State.NORMAL);


    Also if it allows you to combine a declaration with an assignment:


    AcctState acctState=balance<0 || monthTxCount>20 ? State.WATCH : State.NORMAL;


    Sure, I could have declared the variable and then had an IF statement to assign the value, but that would turn one line into five.

    And/or if the destination involves a complex expression:


    getCustomer(acctNumber).acctState[periodEnd+1)=balance<0 || monthTxCount>20 ? State.WATCH : State.NORMAL;


    Sure, I could do that one with an IF, but then both ends of the IF would have to repeat that whole complex expression describing where the value goes, which means that a reader would have to stop and figure out that the expressions are the same in both cases. (And of course, sooner or later someone would come along and change one but not realize he needs to also change the other.)

    I avoid using it when any of the three expressions pass a certain threshold of complexity, because then it just gets hard to read.

    I never, ever nest them. That's hard to read.

    And the absolute worst use of a ?: I've ever seen -- stumbled across this one a couple of months ago:


    boolean status = getStatus() ? true : false;




    We use a convention where ternaries select between to choices of data rather than code (that would be a job for if).

    That said a properly formatted cascading ternary makes for a nice compact look-up table:

    # Condition # Value

    my $post = $comment_number == 1 ? 'Frist psot 111 eleventy-one'

    : $comment_number == 2 ? 'The Real WTF'

    : $comment_number == 3 ? 'Not really a WTF'

    : $comment_number == 4 ? 'FILE_NOT_FOUND'

    : $comment_number == 5 ? 'Brillant'

    : $comment_number == 6 ? 'Where\'s the wooden table'

    : $comment_number == 7 ? 'Needs more XML'

    : "This wouldn't have happened if they had used $my_favourite_language in the first place" # (default)

    ;


    (Thanks to ChrisF)
  • Ragnax 2013-07-03 15:49
    epv:
    Why not just use if/else statements? There is nothing wrong with them. Just because it compiles doesn't make it a good idea.


    Because banning a language construct just because bottom of the barrel idiots use it wrong, is both asinine and counter-constructive. Sure, you can ban it and solve a few problems. Now deal with the other 99% of stupidity these people produce because they have no affinity or feeling for writing good, clean code.

    Meanwhile the loss of all the good use cases get under the skin of your talented and actually qualified developers. And then, before you know it someone tries to be clever about it. And then "life, uh... finds a way":

    public static class Ternary
    
    {
    public static T Conditional<T>(bool cond, Func<T> pos, Func<T> neg)
    {
    if ( cond ) { return pos(); }
    return neg();
    }
    }

    return Ternary.Conditional( foo, ()=> "bar", ()=> "baz" );
  • chubertdev 2013-07-03 15:54
    Ragnax:
    Because banning a language construct just because bottom of the barrel idiots use it wrong, is both asinine and counter-constructive. Sure, you can ban it and solve a few problems. Now deal with the other 99% of stupidity these people produce because they have no affinity or feeling for writing good, clean code.


    Yeah, you completely misunderstood his post.
  • lolatu 2013-07-03 15:58
    A:
    Yes, they really should have been more careful and gone for something like:

    initialTab = 0;
    while (isNaN(initialTab)) { initialTab = 0; }

    I was just going to post that myself. Defensive programming is important!
  • chubertdev 2013-07-03 16:10
    lolatu:
    A:
    Yes, they really should have been more careful and gone for something like:

    initialTab = 0;
    while (isNaN(initialTab)) { initialTab = 0; }

    I was just going to post that myself. Defensive programming is important!



    int attempts = 0;
    initialTab = 0;
    while (isNaN(initialTab) || attempts > 10000) { initialTab = 0; attempts++; }
  • nmare 2013-07-03 16:13
    Hotline for ternary abuse:

    We use a convention where ternaries select between to choices of data rather than code (that would be a job for if).

    That said a properly formatted cascading ternary makes for a nice compact look-up table:

    # Condition # Value

    my $post = $comment_number == 1 ? 'Frist psot 111 eleventy-one'

    : $comment_number == 2 ? 'The Real WTF'

    : $comment_number == 3 ? 'Not really a WTF'

    : $comment_number == 4 ? 'FILE_NOT_FOUND'

    : $comment_number == 5 ? 'Brillant'

    : $comment_number == 6 ? 'Where\'s the wooden table'

    : $comment_number == 7 ? 'Needs more XML'

    : "This wouldn't have happened if they had used $my_favourite_language in the first place" # (default)

    ;




    Ok, But why not use a select case statement? Why people need so much to use a "?:" everywhere? it make you feel 1337?
  • twilsonxpert 2013-07-03 17:52
    Nested ternary operators are OK as long as 1. code is formatted property 2. you shouldn't be using a switch instead and 3. you're not using PHP. Which, thankfully, this person isn't. http://phpsadness.com/sad/30
  • Benjamin 2013-07-03 17:58
    ForFoxSake:
    I'm always amazed that in most threads you can find brilliant developers and painful idiots but no one in between.


    That's because everyone in between has the good sense to shut up.
  • techo's R Us 2013-07-03 19:14

    for open bra-a-a-acket var h t m # When Britain first at heav'ns command
    l i-i-i-i-i-n data open pa-arenthesis # Aroze from out the azure main
    quote h t m l quote close pa-are-enthesis # Arose, Arose, Arose from out the azure main
    close bracket dollar, open bracket data # this was their calling, the charter of the land
    open pare-e-e-enthesis quote htm # and guardian angels sang this strain
    l quote clo-ose pare-enthesis open # "Rule Britannia, Britannia rule the waves
    parenthe-e-e-sis h t ml # Britons never, never, never shall be slaves
    close parenthe-sis open parenthesis # "Rule Britannia, Britannia rule the waves
    zero clo-o-o-se pare-enthesis # Britons never, never, never shall be slaves

    We could make it fit to anything. I rememebr seeing a show where people were given a random book and had to sing excerpts to different tunes.
  • Rubbard K 2013-07-03 19:24
    I use ?: when I want an expression's value to be conditional, and if-else otherwise. I avoid nesting them if I need to use parentheses or both branches need to be complex. I think this is excessively verbose:
    if(bar)
    
    x = foo;
    else
    x = baz;

    and should be replaced with
    x = bar ? foo : baz;

    and likewise I'll write
    x = f()? foo : g()? bar : baz;

    instead of
    if(f())
    
    x = foo;
    else if(g())
    x = bar;
    else
    x = baz;
  • fritz with sauce 2013-07-03 19:30
    jay:
    My humble opinion on the "?:" operator (I'll avoid calling it the ternary operator so I don't offend an earlier poster):

    It's handy when you would otherwise have had to declare a temporary variable, for example, if you are passing a value to a function:


    processAccount(acctNum, balance<0 || monthTxCount>20 ? State.WATCH : State.NORMAL);


    Also if it allows you to combine a declaration with an assignment:


    AcctState acctState=balance<0 || monthTxCount>20 ? State.WATCH : State.NORMAL;


    Sure, I could have declared the variable and then had an IF statement to assign the value, but that would turn one line into five.

    And/or if the destination involves a complex expression:


    getCustomer(acctNumber).acctState[periodEnd+1)=balance<0 || monthTxCount>20 ? State.WATCH : State.NORMAL;


    Sure, I could do that one with an IF, but then both ends of the IF would have to repeat that whole complex expression describing where the value goes, which means that a reader would have to stop and figure out that the expressions are the same in both cases. (And of course, sooner or later someone would come along and change one but not realize he needs to also change the other.)

    I avoid using it when any of the three expressions pass a certain threshold of complexity, because then it just gets hard to read.

    I never, ever nest them. That's hard to read.

    And the absolute worst use of a ?: I've ever seen -- stumbled across this one a couple of months ago:


    boolean status = getStatus() ? true : false;



    or

    printf("The process has completed with %d error%s\n", numErrors, ((numErrors!=1)?:"s":"");
  • fritz with sauce 2013-07-03 19:30
    jay:
    chaosprime:
    Today's WTF: reading thedailywtf.com talking about the conditional operator as "the ternary operator".

    Any operator that takes three arguments is a ternary operator.


    We call the receptionist at our company the "unary operator". Because when she forwards a phone call to you, if you give her more than one argument, she just hangs up on you.
    we call ours the urinary operator
  • chubertdev 2013-07-03 19:37
    hmmm (not my code)


    Public Function getFinanceCredit() As Money
    Return (If(isEdited(), (If((Not usePercentage()), editedFixedAmount, (If((percentageOfBasis Is Nothing), NullMoney.NULL_AMOUNT, basis.multiply(percentageOfBasis))))), NullMoney.NULL_AMOUNT))
    End Function
  • Geoff 2013-07-04 02:29
    nmare:
    Hotline for ternary abuse:

    We use a convention where ternaries select between to choices of data rather than code (that would be a job for if).

    That said a properly formatted cascading ternary makes for a nice compact look-up table:

    # Condition # Value

    my $post = $comment_number == 1 ? 'Frist psot 111 eleventy-one'

    : $comment_number == 2 ? 'The Real WTF'

    : $comment_number == 3 ? 'Not really a WTF'

    : $comment_number == 4 ? 'FILE_NOT_FOUND'

    : $comment_number == 5 ? 'Brillant'

    : $comment_number == 6 ? 'Where\'s the wooden table'

    : $comment_number == 7 ? 'Needs more XML'

    : "This wouldn't have happened if they had used $my_favourite_language in the first place" # (default)

    ;




    Ok, But why not use a select case statement? Why people need so much to use a "?:" everywhere? it make you feel 1337?

    Because Java (for example) is sometimes a pain when you are trying to assign to a final field, and conditionals/ternaries (nicely formatted if nested) fit the bill.
  • SkUrRiEr 2013-07-04 03:33
    TheIrritainer:

    $isFrist = (is_null($isFrist)) ? 0 : $isFrist;


    I had a colleague who used that anti-pattern. After carefully and methodically annihilating it from the code base, seeing it again MAKES ME WANT TO CLAW MY EYES OUT!!!!!!

    Thanks, hope you have a nice day!
  • Steve The Cynic 2013-07-04 03:37
    jay:
    And the absolute worst use of a ?: I've ever seen -- stumbled across this one a couple of months ago:


    boolean status = getStatus() ? true : false;

    I see your worst one, and I'll raise you one I saw nearly twenty years ago...
    if( some_condition )
    
    (condition2) ? variable = value : 0;
    else
    something_else;
  • gallier2 2013-07-04 06:21
    [quote user="Steve The Cynic"]
    if( isEdited() )
    
    {
    if( !usePercentage() )
    return editedFixedAmount;
    else if( percentageOfBasis == null )
    return NullMoney.NULL_AMOUNT;
    else
    return basis.multiply(percentageOfBasis);
    }
    else
    return NullMoney.NULL_AMOUNT;
    [/quote]
    Or alternatively, in English-like:
    [quote]If the thingy was edited, then use the percentage times the basis if we are using a percentage and one is available, or if we are not using a percentage, use the fixed amount. If none of the above conditions are met, use the null amount.[/quote]
    In general, I'd prefer to invert the is-null test so that the positive "use-something" conditions are clumped together, and I'd prefer a function "useFixedAmount()" that is equivalent to "!userPercentage()" so that the test looks more related to the code in the branches, but it's reasonably clear.
    [quote]
    if( isEdited() )
    
    {
    if( useFixedAmount() )
    return editedFixedAmount;
    else if( percentageOfBasis != null )
    return basis.multiply(percentageOfBasis);
    else
    return NullMoney.NULL_AMOUNT;
    }
    else
    return NullMoney.NULL_AMOUNT;
    [/quote]
    Better?[/quote]

    Even better, thanks to the return, there's no need for else clauses.
    if( isEdited() )
    
    {
    if( useFixedAmount() )
    return editedFixedAmount;

    if( percentageOfBasis != null )
    return basis.multiply(percentageOfBasis);
    }
    return NullMoney.NULL_AMOUNT;
  • eViLegion 2013-07-04 07:16
    techo's R Us:

    for open bra-a-a-acket var h t m # When Britain first at heav'ns command
    l i-i-i-i-i-n data open pa-arenthesis # Aroze from out the azure main
    quote h t m l quote close pa-are-enthesis # Arose, Arose, Arose from out the azure main
    close bracket dollar, open bracket data # this was their calling, the charter of the land
    open pare-e-e-enthesis quote htm # and guardian angels sang this strain
    l quote clo-ose pare-enthesis open # "Rule Britannia, Britannia rule the waves
    parenthe-e-e-sis h t ml # Britons never, never, never shall be slaves
    close parenthe-sis open parenthesis # "Rule Britannia, Britannia rule the waves
    zero clo-o-o-se pare-enthesis # Britons never, never, never shall be slaves

    We could make it fit to anything. I rememebr [sic] seeing a show where people were given a random book and had to sing excerpts to different tunes.


    Yes... but the point is... ANYTHING can be MADE to fit ANYTHING.

    That doesn't mean that it naturally "fits", which is what is meant when you say "oh look... these words fit to that tune".

    If you say that about something that doesn't naturally fit, but which can be made to do so in a clunky and unsatisfactory way, then you're saying nothing of value, and you're sounding like an idiot while you do it.
  • qbolec 2013-07-04 11:15
    You can find it easier to fit your speach into a tune using https://play.google.com/store/apps/details?id=com.smule.autorap&hl=pl
  • Yazeran 2013-07-04 14:10
    jay:
    chaosprime:
    Today's WTF: reading thedailywtf.com talking about the conditional operator as "the ternary operator".

    Any operator that takes three arguments is a ternary operator.


    Any prime number that is divisible by 2 is an "even prime". However, I don't think it creates a great deal of ambiguity to talk about "the even prime", because there is only one.


    Well I gyuess I'm in a somewhat whacked state today, as I read the shell line in the article as
    if ($horror = ...
    instead of
    if ($error = ...
    Which seemed somehow more correct.

    And now I read your line as "the evil prime"....

    I guess I need more coffee


    Yazeran

    Plan: To go to mars one day with a hammer.
  • Neil 2013-07-04 19:05
    The best thing about ternary expressions is that you've got so many ways of writing them. For example you might hate using the ! operator in a ternary condition, which results in code like this:
    public Money getFinanceCredit() {
    
    return isEdited() ? usePercentage() ? percentageOfBasis ? basis.multiply(percentageOfBasis)
    : NullMoney.NULL_AMOUNT
    : editedFixedAmount
    : NullMoney.NULL_AMOUNT;
    }
    or alternatively you might hate nesting ? : between ? and :, which results in code like this:
    public Money getFinanceCredit() {
    
    return !isEdited() ? NullMoney.NULL_AMOUNT :
    !usePercentage() ? editedFixedAmount :
    !percentageOfBasis ? NullMoney.NULL_AMOUNT : basis.multiply(percentageOfBasis);
    }
  • Rob G 2013-07-05 05:53
    I really wish you'd never mentioned this!
  • not else 2013-07-05 13:35
    I'm a fan of Edsger Dijkstra and "grew up" on structured programming. By using if blocks the steps are clearly defined, reducing the chance of inserting operations incorrectly between the return statements.


    result = NullMoney.NULL_AMOUNT
    if isEdited()
    if useFixedAmount()
    result = editedFixedAmount
    elsif percentageOfBasis != null
    result = basis.multiply( percentageOfBasis )
    endif
    endif
    return result
  • nmare 2013-07-05 15:56
    not else:
    I'm a fan of Edsger Dijkstra and "grew up" on structured programming. By using if blocks the steps are clearly defined, reducing the chance of inserting operations incorrectly between the return statements.


    result = NullMoney.NULL_AMOUNT
    if isEdited()
    if useFixedAmount()
    result = editedFixedAmount
    elsif percentageOfBasis != null
    result = basis.multiply( percentageOfBasis )
    endif
    endif
    return result


    This is exacly why you should not use a "?:" in a normal situation! Code is harder to maintain.
  • jay 2013-07-05 16:26
    nmare:
    Hotline for ternary abuse:

    We use a convention where ternaries select between to choices of data rather than code (that would be a job for if).

    That said a properly formatted cascading ternary makes for a nice compact look-up table:

    # Condition # Value

    my $post = $comment_number == 1 ? 'Frist psot 111 eleventy-one'

    : $comment_number == 2 ? 'The Real WTF'

    : $comment_number == 3 ? 'Not really a WTF'

    : $comment_number == 4 ? 'FILE_NOT_FOUND'

    : $comment_number == 5 ? 'Brillant'

    : $comment_number == 6 ? 'Where\'s the wooden table'

    : $comment_number == 7 ? 'Needs more XML'

    : "This wouldn't have happened if they had used $my_favourite_language in the first place" # (default)

    ;




    Ok, But why not use a select case statement? Why people need so much to use a "?:" everywhere? it make you feel 1337?


    Or a nested IF? What's the advantage of the ?: there?
  • chubertdev 2013-07-05 17:33
    jay:
    Or a nested IF? What's the advantage of the ?: there?


    You wouldn't happen to use SFDC's Apex, would you?
  • Muzer 2013-07-06 14:59
    Auld Lang Syne (see page source code/comments) definitely works a lot better for me - I can't get Rule Britannia to fit at all (verse or chorus).
  • Not Safe for Whales 2013-07-07 21:00
    Hotline for ternary abuse:
    We use a convention where ternaries select between to choices of data rather than code (that would be a job for if).

    That said a properly formatted cascading ternary makes for a nice compact look-up table:

    # Condition # Value

    my $post = $comment_number == 1 ? 'Frist psot 111 eleventy-one'

    : $comment_number == 2 ? 'The Real WTF'

    : $comment_number == 3 ? 'Not really a WTF'

    : $comment_number == 4 ? 'FILE_NOT_FOUND'

    : $comment_number == 5 ? 'Brillant'

    : $comment_number == 6 ? 'Where\'s the wooden table'

    : $comment_number == 7 ? 'Needs more XML'

    : "This wouldn't have happened if they had used $my_favourite_language in the first place" # (default)

    ;


    (Thanks to ChrisF)
    How dare you!

    You forgot Irish Girl!
    CAPTCHA = mara
  • Blab 2013-07-08 03:37
    Maybe comedy shouldn't be analyzed...
  • The Big Picture Thinker 2013-07-09 14:43
    There is a well-known bug in the order of operations of PHP ternary operators.

    Always use parentheses for nested ternaries in PHP, or this will happen:

    http://www.phpsadness.com/sad/30
  • stew 2013-07-09 16:21
    Niko:
    TRWTF is, as usual, PHP.

    <example of PHP's conditional operator behavior>
    So while technically accurate, I see no actual relevance to the article, as that particular example wasn't written in PHP.

    But we get it: you don't like PHP. A remarkably audacious stance that I'm glad you felt necessary to share.
  • Arancaytar 2013-07-18 04:35
    This particular line can be sung to the tune of “Rule Britannia”.

    for (var html in data["html"])
    $(data["html"][html][0]).html(data["html"][html][1]);


    I'm not sure how the hell you need to pronounce HTML for that to work. Is the dollar silent?
  • Arancaytar 2013-07-18 04:40
    Not Safe for Whales:
    Hotline for ternary abuse:
    We use a convention where ternaries select between to choices of data rather than code (that would be a job for if).

    That said a properly formatted cascading ternary makes for a nice compact look-up table:

    # Condition # Value

    my $post = $comment_number == 1 ? 'Frist psot 111 eleventy-one'

    : $comment_number == 2 ? 'The Real WTF'

    : $comment_number == 3 ? 'Not really a WTF'

    : $comment_number == 4 ? 'FILE_NOT_FOUND'

    : $comment_number == 5 ? 'Brillant'

    : $comment_number == 6 ? 'Where\'s the wooden table'

    : $comment_number == 7 ? 'Needs more XML'

    : "This wouldn't have happened if they had used $my_favourite_language in the first place" # (default)

    ;


    (Thanks to ChrisF)
    How dare you!

    You forgot Irish Girl!
    CAPTCHA = mara


    I was going to suggest switch, but it turns out PHP can't even take advantage of jump tables, and will convert it to chained ifs anyhow.