Thursday, November 28, 2024

PowerFx Formatting If Statement Idiosyncrasies

Disclaimer: This entire blog is an opinion, and opinions are like butts, we all have one.  This is not doctrinal truth that must be observed or else you “are dead to me”.  It is just my opinion which I offer with my reasoning in the hopes that it will convince others to make their low-code developer lives and the lives of those that come after them, better. (If you do disagree with, I would love to hear your counter arguments in the comments)

Auto Formatting If Statements Sucks Has Room For Improvement

This is how a simple if statement is auto-formatted within the Canvas Apps:



This is better than a single line, but still sucks has room for improvement.

  1. "If(" does not require it’s own line to distinguish itself from the surrounding code.  The indentation already serves that purpose and vertical spacing in large PowerFx functions is at a premium (but yet it’s premium-ness shouldn’t override readability, more on that later).
  2. The parts of the if are not clearly distinguished as it contains a single uninterrupted block of text .  This is an extremely simple "if" statement, but it takes a lot of attention to visual detail (aka brain power/cognitive load) to separate the condition portion, the true-statement, and the false/else-statement(s).  This leads to bugs and increases the time required to understand what the code is, what it is doing, and what changes may need to be made.

By including the condition on the same line as the if, and most importantly SEPERATING ELSE/ELSE-IF’S WITH AN UNINDENTED COMMA, each part of the if statement becomes clearly defined, and it takes up no less vertical space than before:



This becomes even more important on longer if statements, or if statements with an else/if:



Although vertical spacing is at a premium in PowerFx (all programing languages really), it should always be subservient to readability.  For longer more complicated if statements, readability should be win out, and the parts of the condition can be split among multiple lines, but double indented to clearly define where the true-statement starts:



The choosing of when to split up the if-condition among multiple lines vs keeping it on a single line is much more personal preference than anything else, and is one that may personally fluctuate from time to time (or at least it does for me).

One final thing to note, eliminating an if statement usually results in cleaner code.  In cases where there is just an if statement used to set a Boolean value, removing it is simple and should be done in almost all situations, just like this one:



Happy coding formatting!

1 comment:

  1. As for the And / Or I prefer a lot the formula syntax and another indentation within it :
    And(
    aPrettyLongFunctionReturningABooleanValue,
    anotherPrettyLongCondition
    )
    I keep your coma indentation in mind as it really improve readability ! thanks

    ReplyDelete