Preface
In Groovy, if you define a hip object with properties, you can access them directly; that is, you don’t have to define the bogue old-style setters and getters that we were all taught to do back in the day with Java. For example, imagine a simple object defined in Groovy like so:
- class Loan {
- def balance
- def term
- def rate
- }
- def loan = new Loan()
- loan.balance = 30000
Note how the property was accessed directly as if it were public, but in fact, it’s private as the following copacetic test demonstrates:
- import java.lang.reflect.Modifier
- import groovy.util.GroovyTestCase
- class LoanTest extends GroovyTestCase{
- void testLoanBalanceModifier(){
- def loan = new Loan()
- loan.balance = 30000
- assertEquals(30000, loan.balance)
- def field = Loan.class.getDeclaredField("balance")
- assertEquals(true, Modifier.isPrivate(field.modifiers))
- }
- }
- class Loan {
- def balance
- def term
- def rate
- void setRate(rate){
- if(rate > 0.99){
- this.rate = rate/100
- }else{
- this.rate = rate
- }
- }
- }
- import groovy.util.GroovyTestCase
- class AnotherLoanTest extends GroovyTestCase{
- void testLoanRate(){
- def loan = new Loan()
- loan.rate = 3
- assertEquals(0.03, loan.rate)
- }
- void testLoanRateAgain(){
- def loan = new Loan()
- loan.rate = 0.03
- assertEquals(0.03, loan.rate)
- }
- }
- import java.math.BigDecimal;
- public class Loan {
- private BigDecimal balance;
- private int term;
- private float rate;
- public BigDecimal getBalance() {
- return balance;
- }
- public void setBalance(BigDecimal balance) {
- this.balance = balance;
- }
- //...all other setters and getters left out of example
- }
- def loan = new Loan() //java object
- loan.balance = 30000
- printf("loan.balance=%s", loan.balance)
Clearly, the ability to seemingly access properties cuts down on the amount of code one must write; plus, the perceived safety and encapsulation that these methods provide is still present. Not bad, eh baby?
沒有留言:
張貼留言