Loan Pattern as the name suggests would loan a resource to your function. So if you break out the sentence. It would
- Create a resource which you can use
- Loan the resources to the function which would use it
- This function would be passed by the caller
- The resource would be destroyed
As you would see, the advantages are multifold. First, I am not constrained by the function which can use the loaned resource. I can pass any function that I desire. Second, I am not concerned about the creation, destruction of the resource. The loan function takes care of it.
Let us take an example, 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
As you would notice that the code snippet can be improved for confirming to the functional standards but that is not the motive right now. If you notice, apart from all the boilerplating or all the work that needs to be done, a few lines are all that change everytime this function is called.
What if we could pass these 4 lines to the function above and still be able to use the boilerplating. The loan pattern attempts to provide exactly that. You would need to pass the functionality and not worry about the resources.
Let us pull the code that we want to execute into a method of its own
You would see that this method takes connection (which is the resource which would be loaned) as an argument and returns integer.
Now let us look at the base method
Here, we have defined the doLoanSqlCall as a method, which would take another function as an argument. Thus, doLoanSqlCall becomes a higher order function. The function which is taken as an argument should take a connection as an argument and return Int. If you look at the definition of
it does exactly that. Takes connection as the argument and returns an Int. The only thing that executeMySqlFunction does not have to worry about is that how would be create the connection and whether it needs to destroy the connection when it is done. The connection resource is loaned by the other method.
Hence the call becomes
and this is now valid for any other SQL function which follows the format connection=>Int