Clean up your Power Fx by Dropping Explicit Boolean comparisons

Something I frequently notice when reviewing other developers’ canvas applications is explicit Boolean comparisons. While there’s nothing technically wrong this this, it is redundant. If you’re in any kind of consulting or contract work, it’s likely that you won’t be supporting your app forever. And let’s be real, who hasn’t been confused by logic they wrote last week in their own applications they’re actively working on? It makes sense to make your Power Fx code as clear and concise as possible

Let’s say you have a button that’s only enabled for admins. Maybe you have some logic that runs in the app OnStart to determine if this is or isn’t true, and then you set that to a global variable we’ll call gblIsAdmin. Now in the button itself, the DisplayMode property would be dependent on this variable. Something one may write is

If(gblIsAdmin = true, DisplayMode.Edit, DisplayMode.Disabled)

There’s nothing technically wrong with this and it will work. However, the ‘true’ portion of the statement above is unnecessary and instead, we can clean that up by updating it simply to

If(gblIsAdmin, DisplayMode.Edit, DisplayMode.Disabled)

Another pattern I see frequently is comparing a Boolean variable to true or false. This is redundant because a Boolean variable already inherently equals true or false. Going back to our example, let’s say instead of disabling a button for non-admin users, we want to hide it completely. In the Visible property, one may write

If(gblIsAdmin, true, false)

75% of the statement above is unnecessary and we can clean this up by updating it to

gblIsAdmin

One thing to remember when using this shorter logic is to be sure to carefully name your variables. I prefer to make my Boolean variables sound like the question of a yes or no answer when I can so that it’s clear to my future self and/or other developers that the variable is a Boolean.


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *