• BeigeAgenda@lemmy.ca
    link
    fedilink
    arrow-up
    22
    ·
    edit-2
    2 days ago

    Don’t you just love the readability

     a =  a > b ? (b > c ? (a < d ? c : a) : d) : (b < c ? a : d )
    
    • kryptonianCodeMonkey@lemmy.world
      link
      fedilink
      arrow-up
      6
      ·
      22 hours ago

      Weird example. 3 nested conditionals is not the typical use case for a ternary, and 2 of the 5 branches result in a pointless a=a assignment. I agree this is bad code, but it’s just as bad and hard to parss in a normal if-else structure too:

      if (a>b) {
          if (b>c) {
              if (a<d) {
                  a=c;
              }
              else {
                  a=a;
              }
          }
          else {
              a=d;
          }
      }
      else {
          if (b<c) {
              a=a;
          }
          else {
              a=d;
          }
      }
      

      In another situation, though, it’s perfectly readable to have a much more typical ternary use case like:

      a = c > d ? c : d

      And a pair of parentheses never hurt readability either:

      a = (c > d) ? c : d

    • subignition@fedia.io
      link
      fedilink
      arrow-up
      8
      ·
      2 days ago

      this is way more nested ternary operators than I would ever use (which I understand is for the sake of example) but if you rearrange them so that the simplest statements are in the true branches, and use indentation, you can make it at least a little more readable

      a = a <= b ? 
          (b < c ? a : d)
          : b <= c ?
              d
              : (a < d ? c : a);