Posts Extract Method – Tip of week #11
Post
Cancel

Extract Method – Tip of week #11

Refactoring is very essential part of coding. You need to refactor your code, to give optimal result. Visual Studio have an inbuilt option for refactoring your code. Right click – Refactor, today I am going to talk about Extract Method.

Suppose this is my sample code, althogh not good but just to demonstrate.

   27 public void fillControl()

   28     {

   29         try

   30         {

   31             OleDbDataAdapter adapter;

   32             DataSet dataset;

   33             OleDbConnection conn;

   34 

   35             conn = new OleDbConnection();

   36             conn.ConnectionString = “PROVIDER=MICROSOFT.Jet.Oledb.4.0;Data Source=” + Server.MapPath(“mydatabase.mdb”);

   37 

   38             string sqlQuery = “SELECT * from employee”;

   39             adapter = new OleDbDataAdapter(sqlQuery, conn);

   40             dataset = new DataSet();

   41             adapter.Fill(dataset);

   42 

   43             datagrid1.DataSource = dataset;

   44             datagrid1.DataBind();

   45         }

   46         catch (Exception ex)

   47         {

   48             Response.Write(“ERROR :: “ + ex.Message);

   49         }

   50     }

 

In this code you can see there is connection object created. But there may be numerous occasions where I’ll have to use the connection, so rather than writing this code again at that place, what I’ll do is just simply select the two lines of connection right click – refactor – extract method

 

extractmethod

name

After this, all you get is extracted method,

   27 public void fillControl()

   28     {

   29         try

   30         {

   31             OleDbDataAdapter adapter;

   32             DataSet dataset;

   33             OleDbConnection conn;

   34 

   35             conn = ConnectDb();

   36 

   37             string sqlQuery = “SELECT * from employee”;

   38             adapter = new OleDbDataAdapter(sqlQuery, conn);

   39             dataset = new DataSet();

   40             adapter.Fill(dataset);

   41 

   42             datagrid1.DataSource = dataset;

   43             datagrid1.DataBind();

   44         }

   45         catch (Exception ex)

   46         {

   47             Response.Write(“ERROR :: “ + ex.Message);

   48         }

   49     }

   50 

   51     private OleDbConnection ConnectDb()

   52         {

   53         OleDbConnection conn;

   54         conn = new OleDbConnection();

   55         conn.ConnectionString = “PROVIDER=MICROSOFT.Jet.Oledb.4.0;Data Source=” + Server.MapPath(“mydatabase.mdb”);

   56         return conn;

   57         }

 

So now you can use this ConnectDb() function where ever you need to use the Database connection.

This post is licensed under CC BY 4.0 by the author.