Expression is a new data type included in GeneXus X that evaluates formulas and expressions at runtime, which can be created by the user or business analyst.
Steps to follow to use this data type in our code:
• First, create a variable of Expression (&exp01) type, indicating the formula or expression to evaluate, in this case a*b+c, assigning it in the &exp01Expression variable of character type.
To define an Expression you can use a combination of arithmetic and relational operators and operands, as well as GeneXus procedures (as long as they follow a certain entry/output structure).
1)
&exp01Expression = "a*b+c" &exp01.Expression = &exp01Expression
|
• Next, assign values to the operands of said formula; in this case, note that the a, b and c operands should be assigned the corresponding value. Let’s suppose that the values that need to be evaluated are stored in the &int1, &int2, &int3 variables.
2)
&int1 = 1.11 &int2 = 2.22 &int3 = 3.33 &exp01.Variables.Set( "a", &int1.ToString() ) &exp01.Variables.Set( "b", &int2.ToString() ) &exp01.Variables.Set( "c", &int3.ToString() )
|
• We have everything we need to effectively evaluate them; to do so, the Evaluate method is used as shown below:
3)
&Result = &exp01.Evaluate() |
The result is stored in the &Result variable.
Because the expression is assigned and evaluated at runtime, it’s important that we check for potential errors by using the ErrCode and ErrDescription properties. For example:
4)
If &exp01.ErrCode = 0 // Execution OK! else // an error occured EndIf
|
Continuing with the example above, from the a,b,c operands loaded to the Expression variable, any type of expression could be assigned and dynamically evaluated again without changing a line of code in the application! Below are some examples that could be evaluated:
5)
&exp01Expression = "-a*(-b+c)" &exp01Expression = "a*(b+c)/100" &exp01Expression = "1+2*3+a*(b+c)/4" &exp01Expression = "log( a * b + c)" &exp01Expression = "abs( a * b + c)" &exp01Expression = "iif( a < b , a , c)"
|
You can also define expressions that use different operands; note that the associated values must be loaded before using the Evaluate method as explained in step 2.
In general, if you need to evaluate an expression at runtime remember that you can use the Expression data type. You only have to define the expression to evaluate, load its respective operands and evaluate it.
GeneXus X productivity. |
Several features make it possible to program less and declare more, as well as to reuse the generated code. In addition, the increase of usability, integration and automation make development simpler, more effective and productive.
In the Community Wiki, read about other features that increase productivity.
|