Thursday, 7 March 2013

Loan pattern in Scala

Loan pattern is really coming from loaning some context to some block, which doesn't care about lifecycle of the context, just using it (as you can find isn't not real world loan, but it work in magic Scala's borders;-)).
A lot of boilerplate in Java can't be avoided when we have to work with connection, resources, threads and etc.

for example:

val out: OutputStream = getOutputStream()
try {
out.write(response.getBytes())
out.flush()
}
finally {
out.close()
}
view raw stream.sc hosted with ❤ by GitHub

Essence is writing to stream, 1 line of code in our case, others aren't part of payload, just a ritual. It's easy to ignore the extra work when we do it once, but reaping it pushes to get ride of such boring staff. Lets introduce high order function which incapsulates the stream management:
withOutput(f: OutputStream => Any) {
val out: OutputStream = getOutputStream()
try {
f(out)
out.flush()
}
finally {
out.close()
}
}
view raw fun.sc hosted with ❤ by GitHub
and the way how we do use it.
withOutput { out => out.write(response.getBytes()) }
view raw fun.sc hosted with ❤ by GitHub
Actually that is one of the most used patterns in Java library wrapper for Scala. Sometimes it becomes the main style in library itself. For example this gist from Scala STM example:
atomic { implicit txn =>
y() = y() + ", first alternative"
if (x getWith { _ > 0 }) // read via a function
retry // try alternatives or block
} orAtomic { implicit txn =>
y() = y() + ", second alternative"
}
view raw fun.sc hosted with ❤ by GitHub
Extremely good example of encapsulation context lifecycle, end even it's not mentioned explicitly as a parameter, while it's stands after "implicit" keyword.

No comments:

Post a Comment