Forum Discussion

314mp_M0th4's avatar
314mp_M0th4
Resolver I
3 years ago
Solved

Formatting a terrible code

Hello, I have a calculated column for my dataset that labels each row with a new category based on a set of rules. My code for this is long and ugly and poorly readable IMO. This is the code : AltT...
  • AntonioM's avatar
    3 years ago

    Hi 314mp_M0th4 ,

     

    Two things would help a lot here, variables and SWITCH.

     

    For the expressions you're using lots of times, you could use variables instead. Something like,

     

     

    VAR _firstdigit = LEFT('Fjárhagsfærslur_Fact'[Tegundalykill_Nr], 1)

     

     

    This does two things. You only have to type '_firstdigit' (or whatever name you choose - it can be much shorter) instead of the full LEFT function each time. That calculation is also only done once, then the result is referred to each time.

     

    As you're using lots of IFs you'd be better off by using SWITCH(). Switch takes the first argument, then goes down a list of conditions until it finds a match.

     

     

    VAR _firstdigit = LEFT('Fjárhagsfærslur_Fact'[Tegundalykill_Nr], 1)
    VAR _number = 'Fjárhagsfærslur_Fact'[Tegundalykill_Nr]
    
    RETURN
    SWITCH(
        TRUE(),
        _firstdigit in {"4","6"} && NOT(_firstdigit in {"1","2","3"}) && NOT(_number in {"47732", "47792"}),
              "10 Tekjur",
        _firstdigit in ... ,
              "27 Afskriftir",
        ...,
              ...,
        (condition),
              (result)
    )

     

     

    Here the first argument is 'TRUE()', so SWITCH checks each condition until one is true. This gives the same results as having lots of IFs all nested together.

     

    If you want to quickly format some code, https://www.daxformatter.com/ is a really good tool.

     

    One last thing, part of your first condition is this:

     

     

    LEFT('Fjárhagsfærslur_Fact'[Tegundalykill_Nr], 1) in {"4", "6"} && NOT(LEFT('Fjárhagsfærslur_Fact'[Tegundalykill_Nr], 1) in {"1", "2", "3"})

     

     

    The second part here isn't necessary, as any time the first part is true the second is always false (the first digit can't be in both lists at the same time).

     

    Hope that helps.

    Antonio