Sunday, 18 November 2012

The Facade Pattern in .NET

The Facade Pattern provides a unified interface to a set of interfaces in a subsystem. Facade defines a higher level interface that makes the subsystem easier to use.

The Facade Pattern is the simplest of the patterns and it is something that many developers probably used a lot in the past without even knowing that there was a name for it. 

It is all about creating a class that simplifies and unifies a set of more complex classes that belong to some subsystem. However a Facade typically does not hide the complex subsystem but simply provide a different simplified view of it. This means that is always possible to use the complex subsystem when needed and that is theoretically possible to have multiple Facades per subsystem.

This pattern typically use the technique of "wrapping" to accomplish the goal. It is important however to remember that the intent of the pattern is to reduce complexity and not to adapt different interfaces like the Adapter Pattern.

I think that it is not worth creating an artificial example to showcase the Facade Pattern. It is more valuable to show examples of usage in the .NET Framework.

A primitive way to implement a Facade is using a static class.

The most significant example in .NET is surely the class File that provide a simple way to interact with the file system in a very intuitive way instead of using lower level abstractions like streams.

This method hides a lot of complexity. If you look inside the .NET Framework source code you find something similar to this:

An another example of Facade in the framework is the class WebClient that allows to easily download a web page from a server without dealing with the HTTP protocol and the sockets.

The beauty of the pattern is then in its simplicity and obviousness.

In addition of simplifying the access to a subsystem the pattern allows to decouple your client implementation from the subsystem. If future version of the subsystem changes the internal components this will not require to update the client code assuming that the Facade API remains unchanged.

Scope of Local Variables in C# and C++

Consider the following code in C++:

This code actually compile and the output is the following:

The important thing to notice here is that in C++ is possible to declare a variable with the same name in a nested block.

In fact the standard documentation say:

"A name declared in a block is local to that block; it has block scope. Its potential scope begins at its point of declaration and ends at the end of its block. A variable declared at block scope is a local variable."

In C# this is not possible. The following code does not compile:

In C# you cannot declare another local variable with the same name in the current block or in any nested blocks. In addition, the variable scope extends in both directions throughout its code block. 

Even the following code does not compile:

I would say that the restriction imposed by C# is good and avoid unexpected behaviours in some situations. It also encourages to use meaningful names for variables avoiding to reuse the same variable for different purposes.

However, the following C# code compiles:

This because the two blocks are not related to each others. They are not part of the same chain of nested blocks. This is good because there is a typical situation when you like to reuse the same variable name in loops. 

This code compiles:

The Adapter Pattern in .NET

The Adapter Pattern converts the interface of a class into another interface the clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

The pattern is also called "Wrapper" because it is usually implemented using the technique of wrapping objects (object composition).

There are different situation when the pattern can be useful but a typical scenario is when you create an abstraction above code that is likely to change in the future. In this way, instead of changing the client code in the future the only thing to do will be implementing a particular adapter.

Let's see immediately an example.

Instead of defining an abstraction myself, I decided to base my example on the  DbDataAdapter class available in the .NET Framework that defines an abstraction for data access operations. 

Suppose we have a simple application that print the list of all the customers extracted from a local SQL server database.

This is an example of execution:

Suppose that a new vendor release a special file based database with the following code.

Assume the following new requirement:

  • Use the new file database instead of SQL Server

It is obvious that the FileDb interface is completely different and incompatible with the interface expected by the client application.

What do you do?

You can use the Adapter Pattern!

In particular, you can create a specific DbDataAdapter class.

Of course you need to migrate the data from SQL Server to the file database:

The beauty of the pattern is that you don't need to change the client code. The only thing that you need to do is to simply use the new FileDbDataAdapter.

All the changes to implement the requirement are encapsulated in a single class: FileDbDataAdapter. 

The designer of the application created the adapter abstraction since the beginning because he was aware that changes of the data access code are highly likely in the future. If this abstraction was not created the change would have been more intrusive that this.

Most of the applications using third party libraries use adapters as a middle layer between the application and the library itself to decouple the application from the library. If another library has to be used only an adapter for the new library is required without having to change the application code.

The main Object Oriented Principles used by the Adapter Pattern are the following:

  • Favor composition over inheritance
  • Encapsulate what varies
  • Program to interfaces, not implementation
  • Open/Closed principle

Saturday, 3 November 2012

The Command Pattern in .NET

The Command Pattern encapsulates a request as an object, thereby letting you parameterize other objects with different requests, queue or log requests, and support undoable operations.

The formal definition of the pattern is quite general and it shows how the pattern is versatile and can be used in many scenarios but the real important thing however is the first sentence, the idea that you can define a command in order to encapsulate a request to do something and use that command as a normal object. 

The Command Pattern allows you to encapsulate a method invocation.

The biggest benefit is separating the object making requests from the objects that receive and execute the requests. 

In order to describe the pattern I will implement a very simple transactional installer.

Let's assume we have the following requirements:
  1. The installer allows you to execute an operation
  2. The installer is independent by the specific operation executed
  3. The installer is able to roll back an operation in case of errors
  4. The installer is able to execute multiple operations as a transaction that is if something goes wrong all previously executed operations will be rolled back
The Command Pattern is the best way to solve this problem.

Let's start to define the command abstraction:

We can easily satisfy the first three requirements defining an installer that accept an instance of the command and calls its methods when requested.

As you can see, the Installer class is completely independent by the specific command that is provided in its constructor. In the same way, the command itself is also completely independent by the Installer.

You can define as many commands as you want:

You can easily create a program to execute some operations:

Super easy isn't it?

What about supporting transactions?

It is here that the real beauty of the pattern comes  in. Because you treat a  command as a normal object, you can aggregate them. Nobody stops you to define a kind of Meta Command that aggregate lots of commands together and in addition implement the support for transactions.

Consider that the TransactionInstallerCommand is still a command. This means that you can use the Installer class without any changes to run a set of commands in a transactional way.

Let's see an example of usage.

Is it not amazing?

In order to simulate an error I created a special command that throws an exception all the time is called.

This is the output of the program:

This example and the Command Pattern is a demonstration of many Object Oriented Principles

Encapsulate what varies

The implementation and the number of each operation is what varies and we encapsulated this creating the CommandInstaller abstraction.

Favor composition over inheritance

The Installer use a Command using composition. The same does the transaction command that compose many commands together in order to create an extremely flexible command.

Program to interfaces not implementations
Depend on abstractions. Don't depend on concrete classes
Strive for loosely coupled designs between objects that interact

InstallerCommand is the main interface introduced here that allows a very loosely coupled design with the Installer.

Classes should be open for extension but closed for modifications

It is very easy to create a new command and you don't need to change the TransactionInstallerCommand in order to use it. TransactionInstallerCommand satisfy the Open/Closed principle.

We didn't finish yet because I am sure you have a question.

In .NET we have delegates and lambda as a way to represent code as an object. At the end of the day, this is what the command pattern is about or not?

This is absolutely true!

.NET developers are now quite familiar with code like this:

If you think carefully the Where method is accepting a command as an input and it is independent by the specific command provided. In this case the command is a predicate that is a function that takes an argument and returns a boolean as the result.

In addition, the predicate requested is just a specific instance of the generic delegate called Func defined as follow:

This Func object is actually the declaration of a generic command.

How would you implement a method similar to Where without having delegates?

Using the Command Pattern of course!

Let's try to do this.

This is an example of usage:

What is wrong about this?

Nothing! However you can easily agree with me that the solution using lambda has a big advantage: you don't need to create a new class all the times you need a new command. 

LINQ has been introduced in the language starting from the version 3.0 of C# and is the biggest implementation in the entire framework of the command pattern using lambdas.

LINQ together with some new features made the C# a better language enabling  some of the most useful features available in so called functional languages.