• 1 Post
  • 274 Comments
Joined 2 years ago
cake
Cake day: July 13th, 2023

help-circle


  • 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















  • Works for code too

    import math
    
    def multiply_bad(a:int, b:int) -> int:
        return a*b
    
    def multiply_better(a:int, b:int) -> int:
        return (-1 if a<0 else 1)*(-1 if b<0 else 1)*int(math.sqrt(a*a*b*b))
    
    def multiply_perfect(a:int, b:int) -> int:
        product = 0
        negative = False
        if a < 0:
            a = -1*a
            negative = not negative
        if b < 0:
            b = -1*b
            negative = not negative
        for i in range(a):
            for j in range(b):
                product += 1
        if negative:
             return -1*product
        return product