Using Constrain instead of If-Then-Else

Updated: July 2020 This article looks at how the constrain block can be used instead of using multiple IF/ELSE blocks.

This is not a one-size-fits-all, and there are definitely times where if statements will be preferable, however, I have found lots of scenarios where this is useful. It is ideal for something like a font size or line width where you want to make sure that the values don’t become too small, or prevent negative values.

If you have more suggestions of places to use this then let me know!

The demo itself is very simple - there are two buttons changing the Slider1 value property of the slider, but obviously this technique will work for any variable in your app.

minmax_design

When the app loads for the first time you’ll need a variable to store the value you’re monitoring, in this case it’s the Slider1 value

The MAX_VALUE is the upper limit for our variable and the MIN_VALUE is our lower limit. Every time a button is pressed the current_value is incremented. To ensure that the value doesn’t go beyond our predetermined constraints we can create the following function:

Now when either of the buttons is clicked you can change the value of current_value and then call the applyConstraints function to make sure it stays within your predefined bounds.

Here’s the project page for this example, please feel free to remix it to take a close look at the blocks:

https://x.thunkable.com/projectPage/5f17ff50dc1a96591900e8a9

12 Likes