5 Tips to condense your Power Fx code
Published at Oct 9, 2023
Table of contents
- If you’re returning a boolean, you don’t need an If() function
- Use string interpolation for more readable concatenation
- Avoid using a LookUp for a record you already have
- There’s no need to set a blank
- If you’re referring to the current control, use Self
If you’re returning a boolean, you don’t need an If() function
Let’s say you’re writing code to go in the Visibility property of a control. Your code will need to return a boolean. You don’t need to explicitly return true or false.
This is not needed:
If ( Gallery1.AllItemsCount > 0, true, false )
This is a better way of doing it:
Gallery1.AllItemsCount > 0
Use string interpolation for more readable concatenation
If you’re concatenating multiple strings together, it’s usually more readable to user string interpolation. This is where you start your string with a dollar sign and then you can place code inside the quotes by wrapping it in curly braces.
The number of quotation marks and ampersands make this difficult to digest:
"Your contact is " & User.FirstName & " " & User.LastName & " from " & User.Country
This is more readable:
$"Your contact is {User.FirstName} {User.LastName} from {User.Country}"
Avoid using a LookUp for a record you already have
It is easy to write code that works and forget about questioninng it. Good practice is to always consider if there might be a better way of doing something. In this case, we’re performing a lookup to get a product, but we’re forgetting we already have access to that record.
LookUp(Products, Product = locShop.'Current Product'.Product)
Instead, just reference the record you already have:
locShop.'Current Product'
There’s no need to set a blank
Similar to the boolean tip above, if you want your return value to be blank, use the Coalesce function to only return a value if it exists
Instead of setting a blank:
If( IsBlank(locProduct), Blank(), locProduct.Price )
Change your If() function to use Coalesce(), which only return a value if it exists:
Coalesce(locProduct.Price)
Thanks for this tip, Mike Gowland! If you aren’t already following him, I’d recommend checking out Mike’s blog for incredibly useful Power Platform articles.
If you’re referring to the current control, use Self
If you’re writing Power Fx code inside of a control that you want to refer to, use Self. This will make your code more readable and more understandable.
We wouldn’t know this code is about the current control unless we double-checked the names:
If ( Gal_ProductList_pls.AllItemsCount > 0, Gal_ProductList_pls.Fill, Color.Red )
This code very obviously refers to the current control, and it’s easier to read:
If ( Self.AllItemsCount > 0, Self.Fill, Color.Red )