Facade Pattern

In this article I would like to explore the Façade design pattern. The actual pronunciation is fu’saad. The dictionary meaning of the word Façade is “A showy misrepresentation intended to conceal something unpleasant”

Now let us enter the challenge..

Challenge

You are working on a database application. Frequently you need to execute UPDATE and DELETE SQL queries. Each time there is a need to create the SqlConnection and SqlCommand class, assign the connection to command and execute the query.

The series of activities looks like:

SqlConnection connection = new SqlConnection(“connection string” );

SqlCommand command = new SqlCommand();

command.Connection = connection;

command.CommandText = “UPDATE Customer SET Processed=1”;

command.ExecuteNonQuery();

You need to repeat the same code wherever execute queries are required. How to make this code better?

Definition

“Provide a unified interface to a set of interfaces in a system. Facade defines a higher-level interface that makes the subsystem easier to use.”

Implementation

Using Façade, we can improve the situation. We can find only the query is different in each case – the parameters like connection string is common for the entire application.

SQLFacade.ExecuteSQL(“UPDATE query here..”);

After using the Façade the code will look like above.

The complicated code is being pulled to the background SQLFacade class.

namespace FacadePattern

{

public class SQLFacade

{

public static bool ExecuteSQL(string sql)

{

SqlConnection connection = new SqlConnection(“connection string”);

SqlCommand command = new SqlCommand();

command.Connection = connection;

command.CommandText = sql;

command.ExecuteNonQuery();

return true;

}

}

}

Façade pattern makes code better as depicted in the image below:

clip_image002

Summary

In this article we have seen how to use the Façade pattern to improve our code. It is similar to the use of reusable functions and it pulls out the complications and provides an easier interface for use. The associated code contains the classes we have discussed.

Leave a Reply

Your email address will not be published. Required fields are marked *