Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save brunkb/dd874c14be8baf32d256 to your computer and use it in GitHub Desktop.
Solving Tricky Problems With the Help of Groovy Closures
class InventorySystem {
boolean open(String token) {
// open a socket connection to some back-end mainframe system
println "opening connection to mainframe, token: ${token}"
BigDecimal pricingLookup(String clientId, String itemUuid)
// call the back end system to get the price of an item for a particular client
// send back a mock price as the result:
boolean close() {
// close the socket connection
println "closing connection to mainframe"
class AuthenticationProvider {
String authenticateUser(String username, String password) {
class InventoryApiConnectionFactory {
// these properties would ordinarily be injected
def authenticationProvider = new AuthenticationProvider()
String username = "username"
String password = "password"
def logError(String msg) { println msg } // simulated logger
def withInventoryConnection(Closure c) {
def authenticatedUserToken = authenticationProvider.authenticateUser(username, password)
def connection = new InventorySystem()
def isOpen =
try {
if(isOpen) {
} catch (any) {
logError("Something went wrong: ${any.message}".toString())
throw any
} finally {
class PricingService {
// would be injected
InventoryApiConnectionFactory fac = new InventoryApiConnectionFactory()
def priceLookup(String clientId, String itemUUID) {
fac.withInventoryConnection { connection ->
connection.pricingLookup(clientId, itemUUID)
PricingService ps = new PricingService()
println ps.priceLookup("client1", "item-11-22-33")
Copy link

brunkb commented Jan 6, 2015

InventoryApiConnectionFactory.withInventoryConnection takes a closure as an argument and manages the full lifecycle of the legacy mainframe connection while executing any method exposed by InventorySystem, in this case, pricingLookup. Generally, there would be a corpus of methods to choose from that execute against the back-end system that someone wrote an API for.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment