ScalaKnol: Understanding Loan Pattern


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

def doSqlCall = {
    var conn: Connection = null
    try {    
      val url = "jdbc:mysql://localhost:3306/"
      Class.forName("com.mysql.jdbc.Driver").newInstance()
      conn = DriverManager.getConnection(url + "vikas", "userName", "password")
      val stmt = conn.prepareStatement("insert into employee (id,age) values (?,?) ")
      stmt.setString(1, "1001")
      stmt.setInt(2, "21")
      stmt.executeUpdate
    } catch {
      case ex: Exception => {        
          println("Exception: " + ex.getMessage)              
        }  
    } finally {
      conn.close
    }    
  }

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.

      val stmt = conn.prepareStatement("insert into employee (id,age) values (?,?) ")
      stmt.setString(1, "1001")
      stmt.setInt(2, "21")
      stmt.executeUpdate

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

def executeMySqlFunction(conn:Connection):Int = {
      val stmt = conn.prepareStatement("insert into employee (id,age) values (?,?) ")
      stmt.setString(1, "1001")
      stmt.setInt(2, "21")
      stmt.executeUpdate
}

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

def doLoanSqlCall(f:Connection=>Int) = {
    var conn: Connection = null
    try {    
      val url = "jdbc:mysql://localhost:3306/"
      Class.forName("com.mysql.jdbc.Driver").newInstance()
      conn = DriverManager.getConnection(url + "vikas", "userName", "password")
      
      f(conn)

    } catch {
      case ex: Exception => {        
          println("Exception: " + ex.getMessage)              
        }  
    } finally {
      conn.close
    }    
  }

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

def executeMySqlFunction(conn:Connection):Int

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

doLoanSqlCall(executeMySqlFunction)

and this is now valid for any other SQL function which follows the format connection=>Int

About these ads

About Vikas Hazrati

Vikas is the CTO @ Knoldus which is a group of software industry veterans who have joined hands to add value to the art of software development. We do niche product and project development on Scala and Java. We consult and coach on effective software development and agile practices. With our focus on software craftsmanship you can be assured of a good quality at the right price. To know more, send a mail to info@knoldus.com or visit www.knoldus.com
This entry was posted in Scala and tagged , , , . Bookmark the permalink.

3 Responses to ScalaKnol: Understanding Loan Pattern

  1. Pingback: JVM函数式编程资源 | 天天三国杀

  2. Pingback: JVM函数式编程资源 | gong yao

  3. Pingback: ScalaKnol : Loan Pattern Revisited | Knoldus

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s