REWRITING THE FUNCTION WITH PARTIAL APPLICATION AND PRECOMPUTATION IN MIND

This doesn’t look like the end of the line, however. The individual calls to your newly created function are still somewhat redundant, because they accept the trans argument on each line. Again, from the functional programming perspective, partial application and precomputation come to mind, and maybe you find yourself rewriting your function like this:

image

static void FillDatabase3( ) {

  using (var conn = new SqlCeConnection(DBCONNSTR)) {

    conn.Open( );

    try {

      using (var trans = conn.BeginTransaction( )) {

        ExecuteSQL(trans, "create table people(id int, name ntext)");

        trans.Commit( );

      }

 

      using (var trans = conn.BeginTransaction( )) {

        var exec = (

          (Func<SqlCeTransaction, Func<int, Action<string>>>)

          (transaction => id => name =>

            ExecuteSQL(transaction, String.Format(

              "insert into people(id, name) values({0}, '{1}')", id, name))))

            (trans);

 

        exec(1)("Harry");

        exec(2)("Jane");

        exec(3)("Willy");

        exec(4)("Susan");

        exec(5)("Bill");

        exec(6)("Jennifer");

        exec(7)("John");

        exec(8)("Anna");

        exec(9)("Bob");

        exec(10)("Mary");

 

        trans.Commit( );

      }

    }

    finally {

      conn.Close( );

    }

  }

}

Code snippet Program.cs

Get Functional Programming in C#: Classic Programming Techniques for Modern Projects now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.