Skip to content

Instantly share code, notes, and snippets.

@christoph-frick
Created October 18, 2014 16:42
Show Gist options
  • Save christoph-frick/f00eb0c7f18d27006bd9 to your computer and use it in GitHub Desktop.
Save christoph-frick/f00eb0c7f18d27006bd9 to your computer and use it in GitHub Desktop.
Fluent groovy API to run and check several steps (code that usually is found in controllers with logs of errors checking) as seen in http://stackoverflow.com/questions/24034324/groovy-code-simplification-and-if-elimination
/* fluent run and test caller to get rid of if-else-cascades */
class RunAndCheck {
final Optional input
Optional output
RunAndCheck(Optional input=null) { this.input = input }
static RunAndCheck start(Closure action) { new RunAndCheck().run(action) }
boolean isFailed() { input && !input.present }
def getValue() { input?.present ? input.get() : null }
RunAndCheck run(Closure action) {
if (failed) {
return this
}
output = Optional.ofNullable(action(value))
return new RunAndCheck(output)
}
RunAndCheck check(Closure test, Closure fail) {
if (failed) {
return this
}
if (!test(value)) {
fail(this)
return new RunAndCheck(Optional.empty())
}
return this
}
}
/* some code to test */
class Test {
def success
def content
}
class TestService {
def load(String id) { return new Test(success:id=='test') }
def loadContent(test) { test.content = 'Content' }
}
def testService = new TestService()
def send500 = { println "ERROR 500: internal server error" }
def send404 = { println "ERROR 404: not found" }
def sendSuccess = { test -> println "Success: $test.content" }
/* run and check */
RunAndCheck.start({testService.load('test')})
.check({it.success}, send500)
.check({!it.content}, send500)
.run({testService.loadContent(it); it}) // must return
.check({it.content}, send404)
.run(sendSuccess)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment