9.4. Externalizing Logic with an Expression Language
Problem
You need to capture application logic in an external file.
Solution
Use an external properties file to store expressions used in an application.
For this recipe, imagine yourself creating a system to sort
Ball objects based on a set of arbitrary criteria.
Instead of hard-coding criteria in a series of Java
if-else clauses, create a
framework with loads sorting criteria from a properties file
containing boolean JEXL expressions. For instance,
the first line in this properties file would be:
Hvy-Green-Basket = ball.color == 'Green' && (ball.weight > 1000)
This translates to “If the ball’s
color is Green and the weight is over 1000, put this ball into the
Heavy Green basket.” The name of each property is
the name of the basket into which a Ball matching
the criteria is placed. The contents of the criteria file are:
Hvy-Green-Basket = ball.color == 'Green' && (ball.weight > 1000) Sm-Yellow-bin = ball.color == 'Yellow' && (ball.weight < 100) Transparent-Bin = ball.isTransparent( ) Lrg-Yellow-Basket = ball.color == 'Yellow' &&(ball.weight >= 100) Misc-Bin = true
Each criterion is applied to each Ball object in
the order it appears in the criteria file. The heavy green sorting
criteria is applied first, and each criterion is evaluated until the
last criterion is reached. The last criteria always evaluates to
true—similar to a
switch-case control statement, the “Misc-bin” is the default. The following code reads this criteria file ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access