ScalaKnol : Loan Pattern Revisited

Here I am going to modify the loan pattern described in this article “Scala Knol : Understanding Load Pattern” .

Let us take an example from earlier blog, we have all used connections to get to the database and then we need to destroy the connection so that there are no leaks. OK, we can use the connection factory but let us assume that we do not have that for now. The general code would look like this

Here this is a higher order function which takes a function f as an argument. function f takes connection as an argument and returns Int.
f: Connection => Int

User just need to pass the above function in doLoanSqlCall factory method. Function executeMySqlFunction do not need to worry about the creating and deleting the connection. All these stuff would be handled by the method doLoanSqlCall.

Hence the call becomes

Example given in this article is excellent if function is not expected to return any other value but Integer. It is working fine in case of most of the insert or update operation where Sql operation returns Integer values.

What is a problem is this approach ?

There is a obvious scenario where data is fetched from database then a custom object is created and returned by the function.

Suppose you have to execute following jdbc code and return an object instead of Integer then above described loan pattern will not help you.

Here mysql function is taking Connection as an argument and returning any generic type. ( In this case it is returning Optiont[List[Int]] but it can return any generic type)

So, Function defination is as follows
Connection => R

Now we need a factory method which need to accept a function f: Connection => R , instead of f: Connection => Int. The modified version of doLoanSqlCall is as follows

This version of doLoanSqlCall method will take a function which takes connection as an argument and return Option of any generic type.

Use executeMySqlFunction as closure

Following example explains the practical way of using the loan pattern with the help of closure.

Written by 

Mayank is a polyglot programmer who believes in selecting the right tool for the job. He has more than 8-year experience in Java Platform. He has been a Scala enthusiast ever since he came to know this beautiful language in 2010. He has been developing enterprise applications on the reactive stack. He's a big fan of agile development, scalable software and elegant code. Mayank has extensive knowledge in a huge spectrum of areas of software, and the ability to dive deeply into a new technology and achieve expert level in no-time. He found fun to architect complex systems in the simplest way and quite handy in Design patterns, micro-services & DevOps technologies. On the personal front, he is a marathon runner, spiritual learner & yoga practitioner.

Leave a Reply

%d bloggers like this: