Fluent Interface

In software engineering, a fluent interface is a method for designing object oriented APIs based extensively on method chaining with the goal of making the readability of the source code close to that of ordinary written prose, essentially creating a domain-specific language within the interface [Wiki].

For example for Stablishing a connection to a database and fetch orders data in a table with common developmment.

var connection = new SqlConnection(connectionString);

SqlCommand command = connection.CreateCommand();
command.CommandType = CommandType.Text;
command.CommandText = "SELECT * FROM Orders WHERE OrderId = @OrderId ";

SqlParameter parameter = command.CreateParameter();
parameter.DbType = DbType.Int32;
parameter.ParameterName = "@OrderId ";
parameter.Value = inputOrderId;

var adapter = new SqlDataAdapter();
adapter.SelectCommand = command;

var table = new DataTable();

connection.Open();
adapter.Fill(table);
connection.Close();
connection.Dispose();
command.Dispose();

var orders = new List<Order>();
foreach (DataRow row in table.Rows)
{
    var order = new Order
    {
        OrderId = (int)row["OrderId"],
        OrderedByName = (string)row["OrderedByName"],
        DeliveryAddress = (string)row["DeliveryAddress"]
    };

    orders.Add(order);
}

But of course it can be shorter with using of Fluen Interface

List<Order> Orders= new SqlQuery(connectionString)
    .SetCommandText("SELECT * FROM Orders WHERE OrderId = @OrderId")
    .AddParameter("@OrderId", OrderId, DbType.Int32)
    .GetDataTable()
    .GetList<Order>();

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: