Scripted methods

The code examples shown so far have been isolated lines that are executed immediately. BeanShell also supports scripted methods (also known in procedural languages as functions). The syntax of scripted methods is to have the return type, method name, parenthesized list of formal parameters, and the method body. If the return type is declared and is not the type ‘void’ then the method must return a compatible value via a return statement. If the return type is void then an option return statement must not have a value.

The following example is the classic recursive factorial calculation:

int factorial(int n) {
   if (n == 0)
      return 1;
      return n * factorial(n – 1);

In order to calculate a factorial value the function is called with the parameter of interest:

print("The factorial of 10 is "+factorial(10));

The following shows an example of automated target setting using the Patchworks API:

void setMinimumAnnualTarget(Target target, double level) { 1
   for (int period=1; period< Horizon.periods; period++)   2
      target.setMinimum((float) (level *                   3
                        Horizon.interval[i]), period);
      target.setActive(true);                              4
      target.setMinimumActive(true);                       5

Items to note in this example


The target object reference and target level values are passed in as formal parameters.


The periods field in the Horizon class contains the number of planning periods in the model. The loop starts at period 1 because target values cannot be set in period 0 (before the simulation starts). The loop ends when the index is no longer less than the number of planning periods. The ‘less than’ relationship is tested rather than the ‘less than equal’ because of the zero-based index that Java uses for arrays.


The harvest level is provided as an annual value, and it is multiplied by the number of years in the planning period. The Target.setMinimum method expects a float value, so the double value is explicitly cast to a float.

4 5

The target and minimum target flags are set to active so that the target is included in the goal programming objective function.