Groovy for Domain-specific Languages - Second Edition

(nextflipdebug2) #1

Power Groovy DSL Features


[ 180 ]

Replacing methods


The technique that we use to add a method can also be used to replace an existing
method. When doing so, we can subvert the existing logic of a class. Wouldn't it be
nice if we could change all bank managers' minds as easily as this?:


class BankManager {

boolean approveLoan() {
return false
}
}

given:
def myBankManager = new BankManager()

expect:
myBankManager.approveLoan() == false

when:
BankManager.metaClass.approveLoan = { true }
myBankManager = new BankManager()

then:
myBankManager.approveLoan() == true

Any method can be overridden or added. This includes any of the operator methods,
such a plus(), minus(), multiply(), divide(), and so on. If need be, we can add
operator semantics to any class, even if we have not written it ourselves.


Adding or overriding static methods


To add or override a static method of a class, we just insert the static keyword
before the method name. In this example, we have a BusinessService class
with static methods. If we try to run with this service as a unit test, then the
remoteService object is not wired in and is null. We can get around this by
adding a isRemoteServiceLive method that returns true. This turns out to
be a great way to mock service methods in unit tests:


class BusinessService {
static def remoteService
static boolean isRemoteServiceLive() {
remoteService.isLive()
}
}

http://www.ebook3000.com
Free download pdf