cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
Anonymous
Not applicable

Help me make if statements more succinct

I'm almost embarrassed to be asking such a simple code question but if there is an elegant answer, it will make my app significantly less verbose. 

 

I have many places where I evaluate an expression (which may be several lines to achieve) and do a quick check to see if it's within bound else I return something different. One example is I want to ensure that the following returns a number between 0 and 365. If it does, I want the number, if it doesn't, I want "?".

 

RoundUp(
    Today() - DateValue(
        Right(
            ThisItem.Description,
            Len(ThisItem.Description) - Find(
                "; modified",
                ThisItem.Description
            ) - 6
        ),
        "en-US"
    ),
    0
)

 

 

 

Typically I would do something like 

 

If(Long Expression > Condition, Long Expression, Error value)

 

 

When the expression I am evaluating is several lines as demonstrated above, it's pretty ugly. Is there a more succinct way to handle this short of writing the entire thing twice within the if statement? In other code I would hold this as a variable however that would add even more clutter to my PowerApps as this happens in many, many places and those values are not otherwise useful. 

1 ACCEPTED SOLUTION

Accepted Solutions
timl
Super User
Super User

Hi @Anonymous 

There's no need to be embarrassed about asking, it's a good question 🙂

Judging by how you use ThisItem in your syntax, I assume that you intend to apply this logic in a gallery, or some other control that displays a collection of data. In this case, I would avoid variables because you would potentially need to create a variable for every row of data.

In addition to @v-yutliu-msft  suggestion of placing LongExpression in a label and referring to that, another approach is to add LongExpression to the Items property of your gallery control with the AddColumns function. The expression would look like this:

AddColumns( YourDataSource,
            "LongExpression",
            RoundUp(
                  Today() - DateValue(
                  Right(
                       ThisItem.Description,
                        Len(ThisItem.Description) - Find(
                       "; modified",
                       ThisItem.Description
                      ) - 6
                   ),
                   "en-US"
                   ),
                   0
            )
)

This will add LongExpression as a column to your data source. Once you do that, you can use the syntax that you suggested in your post....

If(LongExpression > Condition, LongExpression, Error value)


Finally, I'd suggest that people vote on this idea of adding Functions/Macros to PowerApps because this could help out in these types of situation.

https://powerusers.microsoft.com/t5/Power-Apps-Ideas/Create-custom-functions-macros/idi-p/6187 

 

View solution in original post

11 REPLIES 11
poweractivate
Super User
Super User

@Anonymous 

 

If you ever reuse the part that you don't want to abstract away into a variable anywhere else then it may be unwise to be so hesitant to abstract it away into a variable.


If you are absolutely sure you never need it again, the nested condition might be actually fine.

 

Otherwise, just double check and see if you are absolutely sure you can't combine the If statements into a single logical check. To do this, look carefully and see if the two if statements have something in common and write a single if statement. Short of that, the nesting may be fine if it is not reused anywhere else. Note that often times something that looks like it isn't needed later actually is - the moment that happens, even if it reused only in one other place, this is where a variable that you are so hesitant in using, likely would probably be better to use in that case.

poweractivate
Super User
Super User

@Anonymous 

 

Here's a more obvious one to look into.

 

Use the && (and) operator to combine the checks into a single instead of nesting - however, that depends - if it's two different things you need to do, maybe you do need to nest.

 

Your question is about Long Expression not needing to be written twice. That already in and of itself is repeating something twice. In our opinion that alone would justify a variable just to reduce repetition - even if only one time - however that's our opinion.

Anonymous
Not applicable

PowerApps can get pretty ugly. Just use //comments and add some extra line break if needed. You can also use Set() to break the end If() statement up into smaller pieces. Also, there's Flow, which is very powerful. If there's a big function you'll use a lot, you can outsource it to Flow and get the result delivered back to PowerApps, which would reduce it to something like YourFlowName.Run(YourArguments).Result

---
If this answered your question, please click "Accept Solution". If this helped, please Thumbs Up.

poweractivate
Super User
Super User

@Anonymous 

 

Your question is about Long Expression not needing to be written twice.

 

That already in and of itself is repeating something twice.

 

In our opinion that alone would justify a variable just to reduce repetition (Don't Repeat Yourself or DRY principle) - even if only one time in the same line - however that's our opinion.

Anonymous
Not applicable

I do agree that repetition is ugly however I'll personally weigh that with careful utilization of my variables as to not create too much abstraction that could be hard for someone else to follow.

 

This is really just a general question of mine to see if I'm missing a trick that people use. I find the situation where I'm evaluating and comparing and then returning the evaluated expression again happens very frequently. I was hoping there was the equivalent of  x++ is the same as x=x+1. 

@Anonymous 

 

Is that huge Round inline expression the one you referred to as "Long Expression"?

 In our opinion, it is worth putting that into a variable.

 

Also if it needs to be changed later (and it may need to, for any number of reasons) - changing it once instead of twice in some long expression is preferable to us, though that's our opinion. 

 

 

RoundUp(
    Today() - DateValue(
        Right(
            ThisItem.Description,
            Len(ThisItem.Description) - Find(
                "; modified",
                ThisItem.Description
            ) - 6
        ),
        "en-US"
    ),
    0
)

 

@Anonymous 

 

Also for performance if you're doing this a lot - although we are unsure of the specific implementation of the underlying engine at this time, writing it inline may run the operation in the underlying engine twice (or maybe even more, depending on the situation) instead of somewhere closer to just once if you set a variable - though we can't be absolutely sure on that. If that is multiplied by a certain number and if our assertion is true, then there may be a performance impact besides a maintenance impact. We cannot be sure on the performance impact though.

v-yutliu-msft
Community Support
Community Support

Hi @Anonymous ,

Could you tell me where do you want to use this formula: RoundUp(....) and how do you want to justify this value?

I assume that you set a label's Text to RoundUp(....), and then you click a check button, of the data is between 0 and 365, the label will retain displaying this data, if isn't, change the label's text and display "?".

I've made a similar test for your reference:

1)set the label's Text:

If(IsBlank(testvar)||testvar="b",
   Text(RoundUp(
             Today() - DateValue(
             Right(
             ThisItem.Description,
             Len(ThisItem.Description) - Find(
                "; modified",
                ThisItem.Description
                    ) - 6
                    ),"en-US"
                                   ),
                   0)
            ),testvar="c","?")

//please notice that you must use Text(RoundUp(....)), because "?" is text type , while the result of "roundup()" is number. If you want them display in one same control, you need to make them data type the same

2)set the check button's OnSelect:

Set(testvar,"a");If(Value(RoundUp(....))>=0&&Value(RoundUp(...))<=365,Set(testvar,"b"),Set(testvar,"c"))

 //Please replace the .... with the formulas that you listed.

use variable to justify situations

If the variable is blank, then the label will display the original data.

If the variable meet the condition, then the label will display the original data too.

If the variable not meet the condition, then the label will display "?".

 

What's more, if you want the label's Text change based on a textinput.

You could also set the Textinput's OnChange to :

Set(testvar,"a");If(Value(RoundUp(....))>=0&&Value(RoundUp(...))<=365,Set(testvar,"b"),Set(testvar,"c"))

To sum up, since you need to change the label's text, so it is a behavior formula, you should set this formula in one behavior property,like a button's OnSelect, a textinput's OnChange, ect.

 

 

 

Best regards,

Community Support Team _ Phoebe Liu
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
timl
Super User
Super User

Hi @Anonymous 

There's no need to be embarrassed about asking, it's a good question 🙂

Judging by how you use ThisItem in your syntax, I assume that you intend to apply this logic in a gallery, or some other control that displays a collection of data. In this case, I would avoid variables because you would potentially need to create a variable for every row of data.

In addition to @v-yutliu-msft  suggestion of placing LongExpression in a label and referring to that, another approach is to add LongExpression to the Items property of your gallery control with the AddColumns function. The expression would look like this:

AddColumns( YourDataSource,
            "LongExpression",
            RoundUp(
                  Today() - DateValue(
                  Right(
                       ThisItem.Description,
                        Len(ThisItem.Description) - Find(
                       "; modified",
                       ThisItem.Description
                      ) - 6
                   ),
                   "en-US"
                   ),
                   0
            )
)

This will add LongExpression as a column to your data source. Once you do that, you can use the syntax that you suggested in your post....

If(LongExpression > Condition, LongExpression, Error value)


Finally, I'd suggest that people vote on this idea of adding Functions/Macros to PowerApps because this could help out in these types of situation.

https://powerusers.microsoft.com/t5/Power-Apps-Ideas/Create-custom-functions-macros/idi-p/6187 

 

Helpful resources

Announcements

Power Platform Connections Ep 15 | L. Baybutt | Thursday, 1 June 2023

Episode Fifteen of Power Platform Connections sees David Warner and Hugo Bernier talk to Microsoft MVP Lewis Baybutt aka Low Code Lewis, alongside the latest news and community blogs.   Use the hashtag #PowerPlatformConnects on social media for a chance to have your work featured on the show.      Action requested: Feel free to provide feedback on how we can make our community more inclusive and diverse.  This episode premiers live on our YouTube at 12pm PST on Thursday 1st June 2023.  Video series available at Power Platform Community YouTube channel.    Upcoming events:  European Power Platform conference – Jun. 20-22nd - Dublin Microsoft Power Platform Conference – Oct. 3-5th - Las Vegas  Join our Communities:  Power Apps Community Power Automate Community Power Virtual Agents Community Power Pages Community  If you’d like to hear from a specific community member in an upcoming recording and/or have specific questions for the Power Platform Connections team, please let us know. We will do our best to address all your requests or questions.   

May 2023 Community Newsletter and Upcoming Events

Welcome to our May 2023 Community Newsletter, where we'll be highlighting the latest news, releases, upcoming events, and the great work of our members inside the Biz Apps communities. If you're new to this LinkedIn group, be sure to subscribe here in the News & Announcements to stay up to date with the latest news from our ever-growing membership network who "changed the way they thought about code".       LATEST NEWS "Mondays at Microsoft" LIVE on LinkedIn - 8am PST - Monday 15th May  - Grab your Monday morning coffee and come join Principal Program Managers Heather Cook and Karuana Gatimu for the premiere episode of "Mondays at Microsoft"! This show will kick off the launch of the new Microsoft Community LinkedIn channel and cover a whole host of hot topics from across the #PowerPlatform, #ModernWork, #Dynamics365, #AI, and everything in-between. Just click the image below to register and come join the team LIVE on Monday 15th May 2023 at 8am PST. Hope to see you there!     Executive Keynote | Microsoft Customer Success Day CVP for Business Applications & Platform, Charles Lamanna, shares the latest #BusinessApplications product enhancements and updates to help customers achieve their business outcomes.     S01E13 Power Platform Connections - 12pm PST - Thursday 11th May Episode Thirteen of Power Platform Connections sees Hugo Bernier take a deep dive into the mind of co-host David Warner II, alongside the reviewing the great work of Dennis Goedegebuure, Keith Atherton, Michael Megel, Cat Schneider, and more. Click below to subscribe and get notified, with David and Hugo LIVE in the YouTube chat from 12pm PST. And use the hashtag #PowerPlatformConnects on social media for a chance to have your work featured on the show.     UPCOMING EVENTS   European Power Platform Conference - early bird ticket sale ends! The European Power Platform Conference early bird ticket sale ends on Friday 12th May 2023! #EPPC23 brings together the Microsoft Power Platform Communities for three days of unrivaled days in-person learning, connections and inspiration, featuring three inspirational keynotes, six expert full-day tutorials, and over eighty-five specialist sessions, with guest speakers including April Dunnam, Dona Sarkar, Ilya Fainberg, Janet Robb, Daniel Laskewitz, Rui Santos, Jens Christian Schrøder, Marco Rocca, and many more. Deep dive into the latest product advancements as you hear from some of the brightest minds in the #PowerApps space. Click here to book your ticket today and save!      DynamicMinds Conference - Slovenia - 22-24th May 2023 It's not long now until the DynamicsMinds Conference, which takes place in Slovenia on 22nd - 24th May, 2023 - where brilliant minds meet, mingle & share! This great Power Platform and Dynamics 365 Conference features a whole host of amazing speakers, including the likes of Georg Glantschnig, Dona Sarkar, Tommy Skaue, Monique Hayward, Aleksandar Totovic, Rachel Profitt, Aurélien CLERE, Ana Inés Urrutia de Souza, Luca Pellegrini, Bostjan Golob, Shannon Mullins, Elena Baeva, Ivan Ficko, Guro Faller, Vivian Voss, Andrew Bibby, Tricia Sinclair, Roger Gilchrist, Sara Lagerquist, Steve Mordue, and many more. Click here: DynamicsMinds Conference for more info on what is sure an amazing community conference covering all aspects of Power Platform and beyond.    Days of Knowledge Conference in Denmark - 1-2nd June 2023 Check out 'Days of Knowledge', a Directions 4 Partners conference on 1st-2nd June in Odense, Denmark, which focuses on educating employees, sharing knowledge and upgrading Business Central professionals. This fantastic two-day conference offers a combination of training sessions and workshops - all with Business Central and related products as the main topic. There's a great list of industry experts sharing their knowledge, including Iona V., Bert Verbeek, Liza Juhlin, Douglas Romão, Carolina Edvinsson, Kim Dalsgaard Christensen, Inga Sartauskaite, Peik Bech-Andersen, Shannon Mullins, James Crowter, Mona Borksted Nielsen, Renato Fajdiga, Vivian Voss, Sven Noomen, Paulien Buskens, Andri Már Helgason, Kayleen Hannigan, Freddy Kristiansen, Signe Agerbo, Luc van Vugt, and many more. If you want to meet industry experts, gain an advantage in the SMB-market, and acquire new knowledge about Microsoft Dynamics Business Central, click here Days of Knowledge Conference in Denmark to buy your ticket today!   COMMUNITY HIGHLIGHTS Check out our top Super and Community Users reaching new levels! These hardworking members are posting, answering questions, kudos, and providing top solutions in their communities.   Power Apps:  Super Users: @WarrenBelz, @LaurensM  @BCBuizer  Community Users:  @Amik@ @mmollet, @Cr1t    Power Automate:  Super Users: @Expiscornovus , @grantjenkins, @abm  Community Users: @Nived_Nambiar, @ManishSolanki    Power Virtual Agents:  Super Users: @Pstork1, @Expiscornovus  Community Users: @JoseA, @fernandosilva, @angerfire1213    Power Pages: Super Users: @ragavanrajan  Community Users: @Fubar, @Madhankumar_L,@gospa  LATEST COMMUNITY BLOG ARTICLES  Power Apps Community Blog  Power Automate Community Blog  Power Virtual Agents Community Blog  Power Pages Community Blog  Check out 'Using the Community' for more helpful tips and information:  Power Apps , Power Automate, Power Virtual Agents, Power Pages 

Microsoft Power Platform Conference | Registration Open | Oct. 3-5 2023

We are so excited to see you for the Microsoft Power Platform Conference in Las Vegas October 3-5 2023! But first, let's take a look back at some fun moments and the best community in tech from MPPC 2022 in Orlando, Florida.   Featuring guest speakers such as Charles Lamanna, Heather Cook, Julie Strauss, Nirav Shah, Ryan Cunningham, Sangya Singh, Stephen Siciliano, Hugo Bernier and many more.   Register today: https://www.powerplatformconf.com/   

Check out the new Power Platform Communities Front Door Experience!

We are excited to share the ‘Power Platform Communities Front Door’ experience with you!   Front Door brings together content from all the Power Platform communities into a single place for our community members, customers and low-code, no-code enthusiasts to learn, share and engage with peers, advocates, community program managers and our product team members. There are a host of features and new capabilities now available on Power Platform Communities Front Door to make content more discoverable for all power product community users which includes ForumsUser GroupsEventsCommunity highlightsCommunity by numbersLinks to all communities Users can see top discussions from across all the Power Platform communities and easily navigate to the latest or trending posts for further interaction. Additionally, they can filter to individual products as well.       Users can filter and browse the user group events from all power platform products with feature parity to existing community user group experience and added filtering capabilities.     Users can now explore user groups on the Power Platform Front Door landing page with capability to view all products in Power Platform.    Explore Power Platform Communities Front Door today. Visit Power Platform Community Front door to easily navigate to the different product communities, view a roll up of user groups, events and forums.

Welcome to the Power Apps Community

Welcome! Congratulations on joining the Microsoft Power Apps community! You are now a part of a vibrant group of peers and industry experts who are here to network, share knowledge, and even have a little fun! Now that you are a member, you can enjoy the following resources:   The Microsoft Power Apps Community Forums If you are looking for support with any part of Microsoft Power Apps, our forums are the place to go. They are titled "Get Help with Microsoft Power Apps " and there you will find thousands of technical professionals with years of experience who are ready and eager to answer your questions. You now have the ability to post, reply and give "kudos" on the Power Apps community forums! Make sure you conduct a quick search before creating a new post because your question may have already been asked and answered!   Microsoft Power Apps IdeasDo you have an idea to improve the Microsoft Power Apps experience, or a feature request for future product updates? Then the "Power Apps Ideas" section is where you can contribute your suggestions and vote for ideas posted by other community members. We constantly look to the most voted Ideas when planning updates, so your suggestions and votes will always make a difference.   Community Blog & NewsOver the years, more than 600 Power Apps Community Blog Articles have been written and published by our thriving community. Our community members have learned some excellent tips and have keen insights on building Power Apps. On the Power Apps Community Blog, read the latest Power Apps related posts from our community blog authors around the world. Let us know if you would like to become an author and contribute your own writing — everything Power Apps related is welcome!   Power Apps Samples, Learning and Videos GalleriesOur galleries have a little bit of everything to do with Power Apps. Our galleries are great for finding inspiration for your next app or component. You can view, comment and kudo the apps and component gallery to see what others have created! Or share Power Apps that you have created with other Power Apps enthusiasts. Along with all of that awesome content, there is the Power Apps Community Video & MBAS gallery where you can watch tutorials and demos by Microsoft staff, partners, and community gurus in our community video gallery.   Again, we are excited to welcome you to the Microsoft Power Apps community family! Whether you are brand new to the world of process automation or you are a seasoned Power Apps veteran. Our goal is to shape the community to be your ‘go to’ for support, networking, education, inspiration and encouragement as we enjoy this adventure together!   Let us know in the Community Feedback if you have any questions or comments about your community experience.To learn more about the community and your account be sure to visit our Community Support Area boards to learn more! We look forward to seeing you in the Power Apps Community!The Power Apps Team

Top Solution Authors
Top Kudoed Authors
Users online (4,367)