if (borrower.creditScore < 600) {
scriptExit.withMessage 'Credit score of 600 required.'
}
// Everyone else qualifies. Find interest rate based on down payment percent.
result.qualified = true
result.message = 'Groovy! You qualify.'
switch (downPaymentPercent) {
case 0..5: result.interestRate = 0.08; break
case 6..10: result.interestRate = 0.075; break
case 11..15: result.interestRate = 0.07; break
case 16..20: result.interestRate = 0.065; break
default: result.interestRate = 0.06; break
}
請注意全局變量 result、borrower、loan 和 property,腳本使用這些變量訪問和設置共享 Java 對象中的值。這些變量名是通過調用 ScriptEngine.put() 方法設置的。
還要注意 result.productName = 'Groovy Mortgage' 這樣的 Groovy 語句。這個語句似乎是直接設置 MortgageQualificationResult 對象的字符串屬性 productName,但是,清單 3 清楚地說明它是一個私有的實例變量。這并不 表示 Java 腳本編程 API 允許違反封裝規則,而是說明通過使用 Java 腳本編程 API,Groovy 和大多數其他腳本語言解釋器可以很好地操作共享的 Java 對象。如果一個 Groovy 語句嘗試設置或讀取 Java 對象的私有屬性值,Groovy 就會尋找并使用 JavaBean 風格的公共 setter 或 getter 方法。例如,語句 result.productName = 'Groovy Mortgage' 會自動轉換為適當的 Java 語句:result.setProductName("Groovy Mortgage")。這個 Java setter 語句也是有效的 Groovy 代碼,可以在腳本中使用,但是直接使用屬性賦值語句更符合 Groovy 的風格。
現在看看清單 5 中的 JavaScript 抵押產品腳本。這個 JavaScript 腳本代表一種政府擔保的貸款,政府支持這種貸款是為了提高公民的住宅擁有率。所以,業務規則要求這是貸款人購買的第一套住宅,而且貸款人打算在此居住,而不是出租獲利。
清單 5. JavaScript 抵押腳本
/**
* This script defines the "JavaScript FirstTime Mortgage" product.
* It is a government-sponsored mortgage intended for low-income, first-time
* home buyers without a lot of assets who intend to live in the home.
* Bankruptcies and bad (but not terrible!) credit are OK.
*/
result.productName = 'JavaScript FirstTime Mortgage'
if (!borrower.intendsToOccupy) {
result.message = 'This mortgage is not intended for investors.'
scriptExit.noMessage()
}
if (!borrower.firstTimeBuyer) {
result.message = 'Only first-time home buyers qualify for this mortgage.'
scriptExit.noMessage()
}
if (borrower.monthlyIncome > 4000) {
result.message = 'Monthly salary of $' + borrower.monthlyIncome +
' exceeds the $4,000 maximum.'
scriptExit.noMessage()
}
文章來源于領測軟件測試網 http://www.kjueaiud.com/