Java Reference
In-Depth Information
So far, we've seen how variables can be bound to arithmetic and logical expres-
sions, and in those cases where the bound expression is a relatively simple one, it
makes perfect sense to use these facilities outright. But what if your binding
expression is a bit more complex? At this point, you could attempt to fabricate a
more complicated binding by combining together any number of arithmetic or
logical expressions. For example, expanding upon a previous example, this time
instead of binding to an expression that finds the maximum of two variables,
a
and
b
, let's bind a variable to the maximum value of three variables,
a
,
b
, and
c
.
Using
if
-
else
expressions, the assignment statement could look something like
this:
var max1 = bind if ((a > b) and (a > c)) a else
if ((b > a) and (b > c)) b else c;
It's not exactly the prettiest code, and it won't win you many friends when the
time comes for a code review. Instead, one preferable substitute might be to del-
egate the computation elsewhere and bind to that result. In essence, it would be a
lot nicer to bind to a function call. Let's take a look at how this can be done.
First, a
getMax()
function could be defined, which takes three arguments and
returns the value represented by the largest of the three arguments. Next, a new
variable, called
max2
, is defined and bound to a call to
getMax()
. The alternative
to the original messy bind expression now looks like
function getMax(i1: Integer, i2: Integer, i3: Integer)
: Integer {
if ((i1 > i2) and (i1 > i3)) { return i1; }
else if ((i2 > i1) and (i2 > i3)) { return i2; }
else { return i3; }
}
var max2 = bind getMax(a, b, c);
If either a JavaFX function call or a Java method call is preceded by the
bind
keyword (in the appropriate context), it will be reevaluated when any of its argu-
ments change. In order to show that the two aforementioned
bind
statements do
the same thing, we'll create two bound variables,
max1
, which is bound to the
compound
if
-
else
clause, and
max2
, which is bound to the
getMax()
function
call, and see what happens when the values of
a
,
b
, and
c
are changed. So:
var a = 1;
var b = 2;
var c = 3;
Search WWH ::
Custom Search