Learning Rules

You can address complex examples using API Creator:
lac42
Rules offer the promise of accelerating backend delivery by an order of magnitude. That is a big promise. But rules are a new paradigm, so there are sensible questions:
  • Complexity.
    How do rules address complex problems?
  • Performance.
     Nothing matters if the system is slow. API Server automates best practices for performance.
    For more information about performance, see Performance.
  • Debugging.
     Are rules a black box or can I address problems easily?
  • Learning.
     Is the paradigm reasonable to learn?
This article addresses these questions.
In this article:
 
 
2
 
 
Verify the Prerequisites
Before you learn the rules, ensure that you have reviewed one of the following:
  • You understand how rules operate.
    For more information about a description of how rules operate, see Reactive Logic Operation.
  • You have watched the following Rule Operation video.

The Promise of Rules
The Check Credit example is a representative transaction, where a insert/update/delete affects multiple related objects.
  • Correctness.
     Building correct code presents its challenges. Reactive programming addresses several of the inherent challenges of quality by automating control flow:
    • Automatic Invocation.
       After you declare a rule, API Creator executes the rule for any use case. In this way, API Creator eliminates an entire class of corner-case bugs (the Customer Balance was not adjusted when the Order was re-assigned to a different account)
    • Ordering.
       Execution is ordered by system-discovered dependencies.
  • Maintainability.
     The same elements that promote correctness make reactive logic easier to maintain. Add/change rules and they execute in the proper order.
  • Clarity.
     Removing the boilerplate change detection/propagation and SQL reveals the intent of the logic. Moreover, the logic is revealed in terms clear to business users. The result: Business users and IT speaking the same language. Logic can reduce the risk of requirement misunderstandings.
  • Conciseness.
     The following code snippet shows the rules:
    Validation
    : return row.CreditLimit >= row.Balance Derive Customer.Balance as
    Sum
    (Orders.AmountTotal where ShippedDate === null) Derive Orders.AmountTotal as
    Sum
    (OrderDetails.Amount) Derive OrderDetails.Amount as row.Price * row.Quantity // JavaScript Expression Derive OrderDetails.Price as copy(Product.Price)
    To provide contrast between the rules approach (reactive programming) and conventional event handlers, the same logic is programmed using conventional approaches. The result was 200-500 lines of code. You can further observe that the rules look like a requirements document that business users can read. The rules promotes communication, which can reduce requirement risks.
Address Complex Examples
You can address complex examples using API Creator:
  • Rules can use JavaScript. 
    You express formula and validation rules in (server-side) JavaScript. Using JavaScript enables conditional logic, such as the following formula to compute an 
    OrderDetails
     amount:
    var amount =
    row.Quantity * row.UnitPrice; // row is the OrderDetails row
    if (row.Quantity !== 0) {
    amount = amount * (100 - 100*row.Discount) / 100;
    }
    return amount;
  • Rules can use JavaScript library facilities.
     You can enable and load your own JavaScript libraries and JARs and call the libraries from your JavaScript, for example:
    if (row.placed_date === null) return new Date(); // moment();
    else
    return row.placed_date;
    For more information about how to load JavaScript libraries and Java JAR files, see Logic Libraries.
  • Provide logic not addressed by rules using events.
     You can provide logic that is not addressed by rules using the integrated event model. For example:
    if ("INSERT" != logicContext.initialVerb && row.amount_total != oldRow.amount_total)
    SysLogic.insertChildFrom("purchaseorder_audit", logicContext);
    For more information about the event model and how to create an event, see Event Rule Types.
  • Rules reduce complexity.
     Ordering, dependency management, and automatic invocation inherently reduce complexity. A few simple rules can solve complex problems, in the same way that a few spreadsheet formulas can solve highly complex numerical problems.
For more information about viewing a series of use cases addressed with a few rules, see Logic Tutorial.
Rule and SQL Activity
API Creator provides a detailed log of all rule and SQL activity, including complete row state for each stage. You can also use the debugger for JavaScript code.
For more information about the log, see Debug.
Learning Rules
Address problems with rules using the following approach.
Differences between Reactive Programming and Conventional Procedural Programming
The following are some observations about some fundamental characteristics that distinguish reactive programming from conventional procedural (Imperative) programming:
  • API Creator builds the object model from the schema
    In conventional procedural programming, you typically must create domain classes, such as Java Persistence API (JPA) objects and Microsoft ADO.NET Entity Framework objects. These domain classes provide access to attributes, related objects, and persistence services to read/write data. You also must keep these classes and services consistent with your schema. In reactive programming, 
    CA Live API Creator
     creates (not code generation) the JavaScript object model and creates a row object type for each base class. 
    CA Live API Creator
     updates this model automatically (for example, if you change the schema) when you reload the schema.
    For more information about the JavaScript object model, see Row Objects.
  • No control flow
    •  
      CA Live API Creator
       invokes rules per changes in referenced attributes.
      In conventional procedural programming, you must explicitly invoke object methods for them to execute. In reactive programming, the rules are similar to event handlers or triggers, but are more granular. They react to a change in the referenced attributes.
    •  
      CA Live API Creator
       orders rules by their dependencies.
      In conventional procedural programming, logic within a method or event handler is ordered. In reactive programming, 
      CA Live API Creator
       orders rules by their dependencies. When you alter the rules, for example, during maintenance or during iterative development, 
      CA Live API Creator
       adjusts the logic flow automatically per the new dependencies.
  • Elimination of Boiler Plate code
    In conventional procedural programming, the bulk of your code is change detection, change propagation, and persistence handling (SQL commands). In reactive programming, 
    CA Live API Creator
     automates change detection, change propagation, and persistence handling. The previous logic is executable.
A Simple Validation Example
The declarative rules are expressions for deriving/validating data. The expression operands are derived from the schema: tables, columns, and foreign key relationships. The rule expressions are entered with a combination of forms and server-side JavaScript functions, such as providing if/else logic and access to libraries.
The following code snippet shows a simple example:
Customer Validation: return row.CreditLimit >= row.Balance
This validation rule ensures that the balance does not exceed the credit limit (else the transaction is rolled back). These rules can also reference related object data, per the JavaScript object model foreign key relationships:
Orders Validation: return row.AmountTotal < row.Customer.MaxAmount
For more information about validation rules, see Validation Rule Type.
A Simple SUM Example
You can handle derived balances by adding another rule, a Sum rule type: 
Customer Validation
: return row.CreditLimit >= row.Balance
Derive Customer.Balance as
Sum
(OrdersList.AmountTotal where ShippedDate === null)
The rule operands, again, are based on the schema; 
OrdersList
 is a defaulted name, which is derived from to a foreign key relationship. These rules are fully executable. After you have created them, you do not need to worry with the details of calling them, ordering them, reading/writing data. API Creator addresses these rules with system RESTful update processing.
For more information:
Rules Automate Logic Patterns
The Simple Sum example illustrates a key to using rules: they work in combination to achieve a desired behavior.
Validate a Sum
This simple "Balance < CreditLimit" example illustrates one of the most common logic patterns: validating a rollup/constrain derived result. Other examples of the pattern:
  • Rollup employee salaries to department, constrain to budget.
  • Rollup departments, constrain to budget.
  • Rollup Student Course Credit, constrain to max for student, max for course.
  • Compute Product Price from the sum of the Component Parts (nested).
  • Compute Event GiftsAmount from sum of EventGifts.
Existence Checks: validations on [qualified] counts
For example, order must have items and department must have employees.
Scale to Complexity
You can identify and automate your own patterns by basing rule definitions on JavaScript. API Creator includes the following examples:
  • Copy.
     Invoke copy, including deep copy, for patterns like auditing or cloning. The copy pattern automates a Bill of Materials explosion.
  • Allocation. 
    Allocate an amount to a set of recipient, such as a bonus to department employees or a payment to outstanding orders.