Facade Design Pattern

Continuing with the Design Patterns Series, this post is about the Facade Design Pattern. Facade is a structural design pattern which provides a unified interface to a set of interfaces in the sub-system. Although this definition is derived from the Gang of Four book, it doesn’t mean that we have to have a set of sub-systems. Later on I’ll try to explain with an example how Facade can be used to improve an existing interface as well. So lets get started.

Problem Statement

For the sake of continuity I’ll use the same example that I had used in the previous post related to State Design Pattern. This time the context will be different and as I have been repeatedly saying during this series on Design Patterns that every time there is a conflict in our mind about which pattern to use, we should see the context of the problem.

Assume we are building software for a bank which deals with Mortgage loans or housing loans. There are various steps which needs to be followed while granting the loan. Assume that you go to a bank and request them for 100000 USD loan, the bank won’t give you all the amount you requested just like that. They’ll follow certain procedures before approving the loan. Even after satisfying all the criteria set by the bank, you might get only fraction of the loan as per the rules and regulations of the bank.

One of the most important step every bank follows before approving the loan is the verification process. At the time of applying the loan you’ll have to submit various documents including your personal details, professional details, financial details etc.Based on these details provided by you the bank will perform the verification and depending on the results will decide to approve or reject your loan application.

Lets say we wish to narrow down our scope a bit and concentrate on only home loans for this blog post. In case of home loans the bank also does verification for the developer or the builder from which you are buying the house to ensure that the developer is a genuine one or not. The bank has a list of preferred builds whose projects are financed by the bank or are pre-approved. But if you are approaching the bank for a project which is not pre-approved or being developed by the preferred developer, that doesn’t mean the bank will simply reject your application. Based on certain conditions, the bank has its own list of blacklisted projects. If the project is blacklisted, then the loan application will be rejected.

Taking these business rules around home loan processing lets start building the software.

Loan Manager without Facade

We have a LoanManager class here which has a Process method. To keep the post simple, assume that the LoanApplication class contains all the details related to the amounts, personal details, professional details etc. For simplicity I’ll not cover these things in this post. Assume that there is some screen or a set of screens which collect all the required details and invoke the Process method which is responsible for approving or rejecting the loan application and informing the applicant about the decision.

    public class LoanManager

    {

        public void Process(LoanApplication application)

        {

            bool personalDetailsAreValid = new PersonalDetailVerifier().VerifyDetails(application);

 

            bool professionalDetailsAreValid = new ProfessionalDetailVerifier().VerifyDetails(application);

 

            bool creditHistoryVerified = new CreditHistoryVerifier().Verify(application);

 

            bool isPreferredDeveloper = new DeveloperVerifier().IsPreferredDeveloper(application.DeveloperName);

 

            bool isProjectApproved = isPreferredDeveloper ? true : new ProjectVerifier().IsBlackListedProject(application.ProjectName);

 

            bool isEligible = personalDetailsAreValid

                && professionalDetailsAreValid

                && creditHistoryVerified

                && isProjectApproved;

 

            application.IsApproved = isEligible;

 

            NotificationService notificationService = new NotificationService();

            notificationService.Notify(application);

        }

    }

Here is the implementation of the Process method. It interacts with various other classes like PersonalDetailVerifier, ProfessionalDetailVerifier, CreditHistoryVerifier, DeveloperVerifier and ProjectVerifier. I have implemented these verifiers as classes. but in real life these will usually be some sort of external services. For example Personal details verification process might involve a phone call to the individual or the person whose details were provided as referral. It could also be done through some Government office based on some unique identity based system. Professional details verification can involve a phone call to the office of the individual or a email communication with the Human Resources department. Credit History verification can involve verification against a central repository of all banks or some other process. And similarly for the developer and the project verification. What I am trying to highlight here is that all these verifiers are basically a distinct systems in their own rights.

Our class LoanManager is tightly coupled with several sub-systems during this process of loan approval. Assume that currently the bank uses a private detective agency for personal and professional verification of the applicant. Due to changes in the regulations the same details can be furnished using a central system developed by the Government. In this scenario we’ll have to modify the LoanManager every time there is some change in the verification system.

Consider another scenario. What if the regulations change and we need to add or modify the existing procedures before approving the loan. In all these scenarios we’ll have to modify the LoanManager class. The example I have shown here is a very simplistic one. More often than not we’ll come across scenarios where we have to make multiple changes. How can we fix this problem.

Refactoring towards Facade Pattern

The Process method depends on the results of the various verifiers. We can follow the commonly suggested method in Gang Of Four book and delegate this responsibility to another object. We can extract the complete verification process into a simplified interface which can aggregate the result of the various sub-systems. In this way our LoanManager class will need to depend upon only one interface and not all the individual sub-systems. Lets look at the refactored code.

    public class LoanManager

    {

        public void Process(LoanApplication application)

        {

            ILoanApplicationVerifier loanApplicationVerifier = new LoanApplicationVerifier();

 

            bool isEligible = loanApplicationVerifier.IsEligible(application);

 

            application.IsApproved = isEligible;

 

            NotificationService notificationService = new NotificationService();

            notificationService.Notify(application);

        }

    }

As you can see, we have abstracted the verification related logic into LoanApplicationVerifier class which implements the interface ILoanApplicationVerifier. The IsEligible method simply returns whether the applicant is eligible or not. By doing so we have made sure that LoanManager need not know exact details about how the verification works. All it needs is the eligibility.

Usage of Facade Pattern within DOTNET Framework

In this example, I have abstracted the verification logic into an interface. It is not always necessary to extract an interface. The Facade pattern can be applied even without having an interface. Look at the objective of the pattern. It is to simplify the sub-system and provide a unified interface. One of the most common example of Facade pattern implementation is the SQLHelper class which was available in the Data Access Application Block provided by the Enterprise Library. It provides a wrapper over ADO.NET. It simplifies the common routine database related activities by providing methods like ExecuteDataSet, ExecuteDataReader etc. You don’t have to worry about the repetitive steps like creating a connection, building a command, executing the command using a data reader.

In my opinion, the complete Enterprise Library itself is a Facade for specific tasks like Logging, Exception Handling, Data Access etc. We use Facade pattern quite regularly without knowing it. For so many years I have been working on applications using layered architecture. The service layer is a big Facade which wraps various underlying services like Authentication, Authorization, Persistence, Logging, Auditing etc. For the end user he or she might be performing a simple action like clicking on the save button, but behind the scenes there are numerous sub-systems which are interacting with one another. In my experience if you are following Model View View Model (MVVM) design pattern or Model View Presenter (MVP) with the model layer being implemented using services and Service Oriented Architecture (SOA), then you are already using Facade pattern.

Conclusion

As we saw from the above examples, Facade pattern helps us to unify various sub-systems and provide a simpler interface. Facade is one of the commonly used design pattern. Sometime we use it even without our knowledge. It is simple to implement. Many a times people get confused between Facade and Adapter design patterns. Based on the class structures they look similar. Once again the intent and the context are useful in deciding which pattern to use. Adapter is used to Adapt an existing interface to a different interface. The Facade pattern provides a new and simplified interface to the existing set of sub systems. The intent in case of Facade is to simply the interaction between various components of the system or application by providing a simpler or unified interface. Adapter makes two incompatible interfaces work together by adapting one to another.

As always the complete working solution is available for download FacadeDesignPatternDemo.zip.

Until next time Happy Programming.

Further Reading

Here are some books I recommend related to the topics discussed in this blog.

spacer

State Design Pattern

This post is the continuation of Design Patterns Series and is related to the State Design Pattern. The State Design Pattern is used when the behaviour of an object changes based on the internal state of the object. Depending on the internal state of the object, the class or the type of the object is changed at the runtime. Lets look at an example to understand this better.

Problem Statement

Assume that we are building a banking software for managing loans of the customers. Loans can be of different types like housing loan, car loan, study loan, personal loan etc. For simplicity we’ll consider only one type of loan here in this example. Lets say that loan type is Personal Loan. The loan goes through different stages during its life cycle. In the beginning the process involves application, then approval, then repayment and finally the closure. We are not considering alternate scenarios like defaults etc. Depending on the current state of the loan, there can be different actions that can be performed. For example when the loan is being applied the applicant can’t pay the monthly instalment. Similarly when the loan is in repayment state and full amount has not been paid, it cannot be closed. Considering these business requirements, lets see how we can build the system.

Loan Manager without State Pattern

We start off with a simple Loan class which has a minimal functionality. We store the current state of the loan along with the approved amount and the outstanding amount.

        public Loan()

        {

            if (CurrentState == null)

            {

                CurrentState = LoanState.Applied;

            }

        }

 

        public LoanState CurrentState { get; private set; }

 

        public int ApprovedAmount { get; set; }

 

        public int OutstandingAmount { get; set; }

Initially, if the current state is not specified, we set the default value as applied. Now there are some business rules. You can make payments only if the loan is in the Repayment state. If the loan is currently in the Approved state, then the Authorized amount and the Outstanding amount are initialized. Imagine this is similar to bank approving your loan application and giving you the money. But payment is not possible in the Applied state and the Closed state. If the loan is not approved yet or it has already been closed as a result of payment of all the dues then there is no point of making any further payment. Based on these combination of rules here is our MakePayment method implementation

        public void MakePayment(int amount)

        {

            switch (CurrentState)

            {

                case LoanState.Reypayment:

                    Console.WriteLine("Updating outstanding amount...");

                    OutstandingAmount -= amount;

                    break;

                case LoanState.Approved:

                    Console.WriteLine("Updating approved and outstanding amount...");

                    ApprovedAmount = amount;

                    OutstandingAmount = amount;

                    break;

                case LoanState.Applied:

                case LoanState.Closed:

                    throw new Exception("Cannot make a payment in Applied or Closed state.");

            }

        }

Similarly, we need to update the state of the loan based on its current state. If the loan is in Applied state then we need to transition it to Approved state. From the Approved state, loan should be transitioned to Repayment state. While the Repayment is processed, if the outstanding amount is zero then we should change the state of the loan to Closed state. Based on these rules lets look at our implementation for the Process method.

        public void Process()

        {

            switch (CurrentState)

            {

                case LoanState.Applied:

                    Console.WriteLine("Updating state to approved from applied...");

                    CurrentState = LoanState.Approved;

                    break;

                case LoanState.Approved:

                    Console.WriteLine("Updating state to repayment from approved...");

                    CurrentState = LoanState.Reypayment;

                    break;

                case LoanState.Reypayment:

                    if (OutstandingAmount == 0)

                    {

                        Console.WriteLine("Updating state to closed from repayment...");

                        CurrentState = LoanState.Closed;

                    }

 

                    break;

            }

        }

Based on this implementation, lets look at a small LoanManager class which uses the Loan class to simulate a loan process.

        public LoanManager()

        {

            // Applied

            Loan loan = new Loan();

 

            loan.Process();

 

            // Approved

            loan.MakePayment(100);

            loan.Process();

 

            // Repayment

            loan.MakePayment(50);

            loan.Process();

 

            // Repayment

            loan.MakePayment(50);

            loan.Process();

 

            // Simulates exception in case of closed loan

            // loan.MakePayment(50);

            // loan.Process();

        }

The comments are explaining the flow of events how the loan transitions from one state to another when we call the Process method.

Problems with current implementation

There are few problems with the current implementation. The two methods MakePayment and Process are dependent on the current state of the loan. There is duplication of the switch statement within both the methods. Imagine what will happen if the business requirement changes and there are other states introduced in addition to the current set of states. For example, if the person who has taken loan does not repay the instalment in stipulated time the loan could go into a Default state.

If we follow the current approach every time there is modification to the list of states either addition or deletion, we will have to modify the two methods Process and MakePayment in our loan class. This is a very simplistic example. But in real applications there could be much more number of methods dependent on the state of the loan. If not corrected in time this can lead to lot of maintenance problems.

Refactoring towards State Pattern

If we observe carefully, the behaviour of the two methods is mainly dependent on the internal value of the current state of the loan. The behaviour changes when the state of the loan changes. In many places in the Gang Of Four book you’ll find advise to abstract what varies and encapsulate it into its own class. We can use this class in our code to comply with the Open Close Principle (OCP). By abstracting the functionality which varies we make sure that our class does not need to change every time there is a change in the varying class. Lets see how we can do this.

We define an abstract class with two methods which vary based on the state.

    public abstract class State

    {

        protected Loan _loan;

 

        public virtual void MakePayment(int amount)

        {

            throw new Exception("Cannot make a payment in current state.");

        }

 

        public virtual void Process()

        {

        }

    }

Each of the states derive from this class and implement the two methods as per their needs.

    public class AppliedState : State

    {

        public AppliedState(Loan loan)

        {

            _loan = loan;

        }

 

        public override void Process()

        {

            Console.WriteLine("updating current state from Applied to Approved...");

 

            _loan.CurrentState = new ApprovedState(_loan);

        }

    }

Here we see the implementation of AppliedState. Notice that the constructor takes the loan instance as an argument and stores it into an instance field. We override the Process method to set the current state to ApprovedState. Lets look at ApprovedState implementation

    public class ApprovedState : State

    {

        public ApprovedState(Loan loan)

        {

            _loan = loan;

        }

 

        public override void MakePayment(int amount)

        {

            _loan.ApprovedAmount = amount;

            _loan.OutstandingAmount = amount;

        }

 

        public override void Process()

        {

            Console.WriteLine("updating current state from Approved to Repayment...");

 

            _loan.CurrentState = new RepaymentState(_loan);

        }

    }

In this case we override both the MakePayment as well as Process methods with respect to the Approved state. With these changes in place lets look at the Loan class.

public class Loan

    {

        public Loan()

        {

            if (CurrentState == null)

            {

                CurrentState = new AppliedState(this);

            }

        }

 

        public int ApprovedAmount { get; set; }

 

        public int OutstandingAmount { get; set; }

 

        public State CurrentState { get; set; }

 

        public void MakePayment(int amount)

        {

            Console.WriteLine("Calling MakePayment on current state");

            CurrentState.MakePayment(amount);

        }

 

        public void Process()

        {

            Console.WriteLine("Calling Process on current state");

            CurrentState.Process();

        }

    }

Instead of storing an Enum value for the current state, now the Loan class stores an instance of the State type. Note the changes to the MakePayment and the Process method. These methods no longer rely on conditional code or switch case logic. Instead they just delegate to the current state instance to perform the appropriate action.

So how does the current state gets updated when there needs to be a transition from AppliedState to ApprovedState or ApprovedState to RepaymentState? This is possible because we pass the loan instance to the concrete state class. If you go back to the Process implementation in the AppliedState or the ApprovedState you’ll find the CurrentState of the passed in loan object being updated.

Conclusion

Using State Pattern we can make the code more maintainable. It is much easier to add or modify the logic if it is related to the state of the object. As we saw in the beginning of the post, if there is state based logic in a class, it can cause lot of duplication in the code. Apart from maintenance, state pattern is helpful in understanding the code flow. If you have a big chunk of switch case logic or if else construct which can transition into various different states, it can be problematic to understand. With State pattern it could be helpful to understand which states can be transitioned into other states very easily. Only disadvantage of State Pattern is that it increases the number of classes in your application.

By using individual states we can focus on the particulars of that state and its transitions. This also helps us in using the Single Responsibility Principle (SRP).

As always the complete working solution is available for download StateDesignPatternDemo.zip.

Until next time Happy  Programming.

Further Reading

Here are some books I recommend related to the topics discussed in this blog.

spacer

Decorator Design Pattern

This post is the continuation of the Design Patterns series. In this post I’ll demonstrate the Decorator Design Pattern. Decorator is a structural design pattern. It is used when we want to dynamically assign responsibility to an object at runtime. Lets look at an example.

Problem Statement

Lets assume we are building software for a store specializing in selling electronic items. Customers can walk into the store and pick the items themselves. Alternately they can also reserve an item over the internet and collect it themselves from the store or have it shipped to their preferred address with an additional delivery charges. Lets build this functionality.

    public class OrderManager

    {

        public OrderManager()

        {

            Order simpleOrder = new Order { Amount = 100, RequiresShipping = false };

 

            int totalAmount = simpleOrder.GetTotalAmount();

 

            Console.WriteLine("Total amount payable : {0}", totalAmount);

 

            Order orderWithShipping = new Order { Amount = 100, RequiresShipping = true };

 

            totalAmount = orderWithShipping.GetTotalAmount();

 

            Console.WriteLine("Total amount payable : {0}", totalAmount);

        }

    }

We have a very simple Order class  which has two properties for storing the Amount and the Boolean flag whether the order requires shipping or not. If RequiresShipping attribute is set to true then we add 10 to the Amount.

Assume that the store is making good business and the online orders have grown exponentially. So the management decides to have premium deliveries which are similar to those orders with shipping, but the exception is that the customer can decide what time slot he wishes to have the delivery. For example, the customer can select a predefined slot like between 5-7 PM on Saturday evening. While the premium delivery customer can select this option, customers choosing normal delivery will be not have such flexibility and can expect the products to be shipped anytime during the day. Lets bake this functionality into the system.

            Order premiumDelivery = new Order { Amount = 100, RequiresShipping = true, IsPremiumDelivery = true };

 

            totalAmount = premiumDelivery.GetTotalAmount();

 

            Console.WriteLine("Total amount payable : {0}", totalAmount);

So in this case we added a new Boolean property to identify if the shipping is premium delivery and added another 10 to the amount along with the shipping charges.

Twist in the tale

After some time the store expands its business model to support international customers. Now we need to add flat 50 to the order amount. Along with the international deliveries, the store is also panning to offer the personalization service to customers. They can have some text engraved on the electronic item. This would cost the customers additional 5 bucks. Customers can also opt for gift wrapping the shipped items at an additional cost of 15 bucks. How do we build these additional requirements into the software?

With the added functionalities, we can have lots and lots of permutations and combinations. Lets take two examples. First one is a domestic customer opting for a premium delivery slot with personalized message and gift wrapping. The second case is international customer with just the gift wrapping. As we can see there can be various other combinations here based on customers choice. The problem with the current solution is that every new requirement will force us to modify the existing code.

Refactoring towards Decorator Design Pattern

If we can come up with a functionality common to all the cases and then add the specific cases it would be really helpful. Since we don’t know beforehand what choices will be made by the user at runtime we need to be flexible enough to ensure various combinations are addressed. This is where Decorator pattern helps us. We can extract the lowest common functionality into an interface or a abstract class. And then the specific cases can override their behaviour by inheriting from the base class or implementing the interface. The way Decorator helps us in adding the functionality at runtime is by composing the objects. Lets look at the implementation to understand this better.

    public interface IOrder

    {

        int GetTotalAmount();

    }

We start with the simplest interface IOrder, which defines the common functionality. In our case an Order is the common thing we have in all cases. The implementation of simple order is very straightforward.

    public class Order : IOrder

    {

        public int Amount { get; set; }

 

        public int GetTotalAmount()

        {

            return Amount;

        }

    }

Nest step is to factor out the dynamic things. We extract this into an abstract class taken an existing order and also implements the IOrder interface. We call this class as OrderDecorator.

    public abstract class OrderDecorator : IOrder

    {

        protected readonly IOrder _order;

 

        protected OrderDecorator(IOrder order)

        {

            _order = order;

        }

 

        public abstract int GetTotalAmount();

    }

Note that the GetTotalAmount method is marked as abstract forcing the derived classes to override it. We start by looking at the LocalShippingOrderDecorator class which implements the domestic shipping functionality.

    public class LocalShippingOrderDecorator : OrderDecorator

    {

        private const int LOCALSHIPPINGCHARGES = 10;

 

        public LocalShippingOrderDecorator(IOrder order)

            : base(order)

        {

        }

 

        public override int GetTotalAmount()

        {

            return _order.GetTotalAmount() + LOCALSHIPPINGCHARGES;

        }

    }

It is straightforward. The overridden GetTotalAmount method delegates the call to the instance of Order class passed in as constructor argument  and also adds the local shipping charges. By doing so we have simplified our design. This confirms to the Single Responsibility Principle (SRP). Our Order class no longer needs to know whether it is for domestic or international shipping. The concerns are separated out to distinct classes. This design also helps us in the Open Close Principle (OCP). As we can see from the next code snippet, we can add InternationalOrderShippingDecorator class can cater to the international customers without impacting local orders.

    public class InternationalOrderShippingDecorator : OrderDecorator

    {

        private const int INTERNATIONALSHIPPINGCHARGES = 50;

 

        public InternationalOrderShippingDecorator(IOrder order)

            : base(order)

        {

        }

 

        public override int GetTotalAmount()

        {

            return _order.GetTotalAmount() + INTERNATIONALSHIPPINGCHARGES;

        }

    }

I’ll avoid displaying the GiftWrapOrderDecorator to save some space here. You can have a look at it in the attached solution file. Next part is bit interesting. Now consider our first case described above. How do we use these classes to fulfil the first case?

            // First case - Domestic customer with premium delivery, personalized message and gift wrap

            IOrder order = new Order { Amount = 100 };

 

            IOrder premiumDelivery = new PremiumOrderShippingDecorator(order);

 

            IOrder giftWrappedOrder = new GiftWrapOrderDecorator(premiumDelivery);

 

            int totalAmount = giftWrappedOrder.GetTotalAmount();

 

            Console.WriteLine("Total amount payable : {0}", totalAmount);

We start by creating the Order and passing it into the premium delivery decorator which is then passed onto the gift wrapper. And finally we invoke the GetTotalAmount on this instance. Instead of creating individual instances and passing them to the decorator classes, we can also choose to go with recursive composition and build the required chain as shown below which caters to the second scenario

            // Second case - International customer with gift wrapping

            IOrder internationalCustomer =

                new InternationalOrderShippingDecorator(new GiftWrapOrderDecorator(new Order { Amount = 100 }));

 

            totalAmount = internationalCustomer.GetTotalAmount();

 

            Console.WriteLine("Total amount payable : {0}", totalAmount);

We have avoided storing the decorators into variables by directly passing them to the constructor. This has the same impact as above.

Examples of decorators within DOTNET framework

There are various examples of Decorator pattern within DOTNET framework. The most common example is the Streams in System.IO namespace. We have the abstract Stream class which acts as the base class for many other streams. We can say that BufferedStream as a classic example of Decorator implementation as its constructor takes an instance of a Stream class and also the BufferedStream inherits from Stream class itself. You can also look at the CryptoStream class which decorates the Stream. DeflateStream and GZipStream classes from System.IO.Compression namespace are also examples of Stream decorators.

Conclusion

Decorator Design Pattern is very handy when we want to dynamically assign responsibility to an object. It can be used to dynamically assign state to an object or to dynamically assign behaviour to an object. The example we saw here was that of dynamically assigning the behaviour to the object. If we correlate the objects  used here in the example with the terminology used within Gang of Four book, our IOrder interface becomes the component and OrderDecorator is the decorator. Order is the concrete component. And all the classes implementing the OrderDecorator abstract class are the concrete Decorators. I have not implemented the PersonalizedMessageOrderDecorator. I leave it as an exercise for readers to implement it.

The advantage of using Decorator is that the class which is being decorated like the Order doesn’t need to know that it is being decorated by some other class. This encourages loose coupling. The component as well as decorator can vary independently.

As always the complete working solution is available for DecoratorDesignPatternDemo.zip.

Until next time Happy Programming.

Further Reading

Here are some books I recommend related to the topics discussed in this blog.

spacer