Connect

  • Connect with me

  • Tuesday, February 28, 2012

    Factory Design Pattern

    In the previous post I had mentioned about Factory Design Pattern. We already had an implementation alongside the Strategy Design pattern. In this post I would like to talk in detail about the Factory Design Pattern. The primary use of factory pattern is to encapsulate the object creation logic from the client. Factory pattern is a creational pattern which helps decoupling the consumers of a class from creating a new instance. Every time we use a new keyword we are tightly coupling the class and its consumer. Factory pattern is also useful when we have a common interface from which we can choose one of the option to create an instance.

    Problem Statement

    Assume that we are building software for a bank. Customers of the bank are entitled to receive the account statement. They can choose the mode of delivery for the statement. It can be a physical statement or an electronic account statement. Based on the customer preference the account statement will be delivered to the customer either in physical paper format or an electronic format in an email.

    Solution

    Similar to the previous post, I don’t intend to use any user interface for this post. Here is a simple AccountStatement class which has a method called DispatchStatement. Based on the input parameter dispatch mode we construct either the PhysicalStatementDispatcher or ElectronicStatementDispatcher instance.

        public class AccountStatement

        {

            public void DispatchStatement(DispatchMode dispatchMode)

            {

                IStatementDispatcher dispatcher = null;

     

                if (dispatchMode.Equals(DispatchMode.Physical))

                {

                    dispatcher = new PhysicalStatementDispatcher

                        {

                            UnitNumber = 101,

                            BuildingNumber = 100,

                            Street = "Little India",

                            PostalCode = 123456

                        };

                }

                else if (dispatchMode.Equals(DispatchMode.Electronic))

                {

                    dispatcher = new ElectronicStatementDispatcher

                        {

                            Email = "JamesBond@hollywood.com",

                            AlternateEmail = "JamesBond@bollywood.com"

                        };

                }

     

                if (dispatcher != null)

                {

                    dispatcher.Dispatch();

                }

            }

        }

    The settings varies based on the type of dispatcher. For the physical statement we specify the details related to the postal address. For the Electronic statement we specify the email address. Finally the Dispatch method is called on the dispatcher instance to dispatch the statement. For simplicity I have hardcoded the values. In real applications these values would come from some persistent data store like database. 

    Problem with this approach

    The problem with this approach are similar to the ones with the previous example related to Strategy pattern. The SRP as well as OCP is violated. The DispatchStatement method contains more than one responsibility. This method knows way too many things like the email address and the postal address of the customer which are not really necessary. Lets try to refactor the solution towards using the Factory pattern. The Factory pattern is a creational pattern which is used to encapsulate the creational logic. In our case we are creating an instance of the dispatcher based on the type of dispatch mode.

    Refactored Solution

    The refactored solution is much simpler and easier to implement.

        public class AccountStatement

        {

            public void DispatchStatement(DispatchMode dispatchMode)

            {

                IStatementDispatcher dispatcher = StatementDispatcherFactory.CreateDispatcher(dispatchMode);

     

                if (dispatcher != null)

                {

                    dispatcher.Dispatch();

                }

            }

        }

    The complete portion of creation of the dispatcher has been moved to the factory. DispatchStatement method delegates the call to CreateDispatcher by passing the dispatch mode. The StatementDispatcherFactory is very simple with just the same code moved from AccountStatement class.

        public static class StatementDispatcherFactory

        {

            public static IStatementDispatcher CreateDispatcher(DispatchMode dispatchMode)

            {

                IStatementDispatcher dispatcher = null;

     

                if (dispatchMode == DispatchMode.Physical)

                {

                    dispatcher = new PhysicalStatementDispatcher

                    {

                        UnitNumber = 101,

                        BuildingNumber = 100,

                        Street = "Little India",

                        PostalCode = 123456

                    };

                }

                else if (dispatchMode == DispatchMode.Electronic)

                {

                    dispatcher = new ElectronicStatementDispatcher

                    {

                        Email = "JamesBond@hollywood.com",

                        AlternateEmail = "JamesBond@bollywood.com"

                    };

                }

     

                return dispatcher;

            }

        }

    By moving the creational logic to the factory we have made the AccountStatement class extensible. We can add more number of dispatchers in future without modifying the AccountStatment class. The OCP is satisfied by moving the creational logic to the factory.

    The other advantage of using the factory is the client need not be aware of the complex construction process. In future we can change the implementation of the one or more dispatcher without impacting the client. Say for example the PhysicalStatementDispatcher is currently using the postal service to deliver the statement and decides to change and use a low cost courier service for delivery of physical statements. This change can be implemented without modifying the AccountStatement class. The account statement class does not need to know who is the provider for the courier service.

    Conclusion

    Factories are very useful when certain decisions are to be made at runtime based on user preferences or environment settings. By encapsulating the creational logic in a central location we can ensure that changes are minimal in the client code. This is very useful when constructing business entities which can be used in multiple places throughout an application. Say for example a business entity is used in 50 places within an application. Due to some new enhancement the constructor parameters needs to be changed. Adding or removing the constructor parameter will impact all those 50 places. We can minimise this change by using factory and centralising the object creation logic within the factory. By just changing the implementation within the factory we can ensure that all the client requests are satisfied.

    While I was working with Tesco, our team had made good use of Factory pattern on almost all the projects that I was involved in. The factories were also helpful during unit testing as they allowed us to return mock instances of the classes.

    As always the complete working solution is available for download.

    Until next time Happy Programming.

    Sunday, February 26, 2012

    Strategy Design Pattern

    Design patterns are reusable solutions to repetitive problems. On various occasions I have seen people writing conditional code. Design patterns help in modularizing the code and making it extensible and maintainable. This post is about how we can refactor conditional logic to better maintainable and cleaner solution using Strategy Design Pattern.

    Problem statement

    Imagine we have to calculate the monthly instalment for a loan. The loan can be of various types for e.g. home loan, car loan, personal loan etc. Each loan can have different duration and also different interest rates. Based on these factors the equated monthly instalments (EMI) will be different. Lets look at a solution without using design patterns and try and refactor the same to one using design patterns.

    For this hypothetical example lets consider that the interest rates for home loan is 10% and car loan is 8%. So we can start building the code to compute the EMI. Lets assume that in both the car and home loan cases the amount is same 100000 and the duration is 24 months. I’ll start by building a set of tests which is easier to get started as I don’t intend to build any user interface for this demo.

    So here are couple of tests I have at this moment

        [TestClass]

        public class CalculatorTest

        {

            private Loan _loan;

     

            private Calculator _calculator;

     

            [TestInitialize]

            public void Setup()

            {

                _loan = new Loan

                {

                    LoanAmount = 100000,

                    DurationInMonths = 24,

                };

     

                _calculator = new Calculator();

            }

     

            [TestMethod]

            public void CalculateEMI_ForHomeLoan()

            {

                _loan.LoanType = LoanType.Home;

     

                decimal expectedInstallment = 4582.6m;

     

                decimal installmentAmount = _calculator.CalculateEMI(_loan);

     

                Assert.AreEqual(expectedInstallment, installmentAmount);

            }

     

            [TestMethod]

            public void CalculateEMI_ForCarLoan()

            {

                _loan.LoanType = LoanType.Car;

     

                decimal expectedInstallment = 4499.28m;

     

                decimal installmentAmount = _calculator.CalculateEMI(_loan);

     

                Assert.AreEqual(expectedInstallment, installmentAmount);

            }

        }

    The implementation is pretty straightforward and self explanatory. The Calculator class below processes the input to calculate the appropriate EMI.

        public class Calculator

        {

            private const int CarLoanInterestRate = 8;

     

            private const int HomeLoanInterestRate = 10;

     

            public decimal CalculateEMI(Loan loan)

            {

                int monthlyInstallment = loan.LoanAmount / loan.DurationInMonths;

     

                decimal interestAmount = 0m;

     

                if (loan.LoanType == LoanType.Home)

                {

                    interestAmount = GetHomeLoanInterestAmount(monthlyInstallment);

                }

                else if (loan.LoanType == LoanType.Car)

                {

                    interestAmount = GetCarLoanInterestAmount(monthlyInstallment);

                }

     

                return monthlyInstallment + interestAmount;

            }

     

            private decimal GetCarLoanInterestAmount(int monthlyInstallment)

            {

                return monthlyInstallment * (CarLoanInterestRate / 100m);

            }

     

            private decimal GetHomeLoanInterestAmount(int monthlyInstallment)

            {

                return monthlyInstallment * (HomeLoanInterestRate / 100m);

            }

        }

     

    Problem with this approach

    On the first attempt this does look fine. The tests are green and the code also has all the ingredients. If we look carefully there are multiple code smells in the above code. Firstly the code violates the Single Responsibility Principle (SRP) principle. The SRP states that there should only be one reason for a class to change. But in the above class there are multiple reasons the class can change. It could change if the interest rate changes. The class will need to be changed if there is change in loan types etc.

    Secondly, it poses a big challenge for maintainability and extensibility. If we are to calculate the EMI for personal loan we need to add another method to calculate the EMI for personal loan. This will have to be repeated for each new type of loan for which we need to calculate the EMI. So in this respect there is another principle which is violated and that is the Open Closed Principle (OCP). The OCP says that classes should be open for extension but closed for modification. This means that we need to encapsulate what varies. In our case the mechanism for calculating the EMI is variable. Lets look at how we can fix this problem.

    Refactored solution

    While refactoring code which is conditional like we have in this example, we can make use of the Strategy Pattern. We can define a strategy for calculating the interest amount. Based on the type of the loan we can call the appropriate strategy. Lets get started with defining a very simple interface for the strategy called IInterestCalculatorStrategy.

        public interface IInterestCalculatorStrategy

        {

            decimal CalculateInterestAmount(decimal monthlyInstallment);

        }

    The interface is very simple and has only one method named CalculateInterestAmount. Lets implement the interest on the home loan. We’ll create a strategy called HomeLoanInterestCalculator which implements the IInterestCalculatorStrategy as shown below

        public class HomeLoanInterestCalculatorStrategy : IInterestCalculatorStrategy

        {

            private const int HomeLoanInterestRate = 10;

     

            public decimal CalculateInterestAmount(decimal monthlyInstallment)

            {

                return monthlyInstallment * (HomeLoanInterestRate / 100m);

            }

        }

    Similarly we implement the CarLoanInterestCalculatorStrategy as

        public class CarLoanInterestCalculatorStrategy : IInterestCalculatorStrategy

        {

            private const int CarLoanInterestRate = 8;

     

            public decimal CalculateInterestAmount(decimal monthlyInstallment)

            {

                return monthlyInstallment * (CarLoanInterestRate / 100m);

            }

        }

    Both the class implementations are exactly same as what was implemented in the solution without strategy as part of the respective methods. But the difference is that the strategies are lot more focussed on individual loan types and are a good way to organize code using SRP. With the strategies in place we refactor the calculator class to make use of one of these strategies.

    Here is the refactored calculator class implementation.

        public class Calculator

        {

            public decimal CalculateEMI(Loan loan)

            {

                int monthlyInstallment = loan.LoanAmount / loan.DurationInMonths;

     

                IInterestCalculatorStrategy calculatorStrategy = CalculatorStrategyFactory.GetStrategy(loan.LoanType);

     

                decimal interestAmount = calculatorStrategy.CalculateInterestAmount(monthlyInstallment);

     

                return monthlyInstallment + interestAmount;

            }

        }

    I have also made use of the Factory pattern in this case. I’ll cover factory pattern in a dedicated post in future. In the context of the current post, it is used to return an instance of the appropriate loan interest calculator strategy based on the type of loan.

    The advantage of using the Strategy Pattern is that we can add any number of loan types in future and the Calculator class will work as expected without any changes. This refactoring has ensured that we followed the OCP by making the Calculator class closed for modification. Since we can add any number of loan types the class remain open for further extension. With addition of another strategy we can get the interest calculated without any change to the Calculator class.

    So lets experiment a bit with this approach. Lets say we want to calculate the monthly instalment for Personal loan. The interest rate for personal loan is 15%. So lets add an implementation as PersonalLoanInterestCalculatorStrategy.

        public class PersonalLoanInterestCalculatorStrategy : IInterestCalculatorStrategy

        {

            private const int PersonalLoanInterestRate = 15;

     

            public decimal CalculateInterestAmount(decimal monthlyInstallment)

            {

                return monthlyInstallment * (PersonalLoanInterestRate / 100m);

            }

        }

    We add a case to the factory to return the new strategy and that is it. There is no need to change anything in the calculator class.

    Conclusion

    When we have lengthy conditional code blocks it can be difficult to maintain and add new features. Factoring the code properly allows us to make changes easily without impacting existing functionality. Strategy pattern is one of the simplest and easiest to understand and implement. It helps to eliminate the conditional logic and makes the algorithms to be used interchangeably. By refactoring the existing code towards Strategy Pattern we can also ensure that we are programming to an interface and not to a concrete implementation. The Calculator class is completely decoupled from the interest calculation concrete implementation.

    The classes are also lot more cleaner and concise. The respective constants related the interest rates are defined in respective strategies. Although the scope of this post is very small I hope it is helpful in demonstrating the intention behind it. The strategy pattern is an ideal refactoring pattern when there are multiple algorithms and they can be used interchangeably. 

    We can look at the code quality metrics to see if this refactoring will be helpful. I ran the code metrics on the solution. In the first version without the strategy pattern, the CalculateEMI method was having the maintainability index of 63. In the refactored solution the same method is having the maintainability index of 70. We can always argue that this is not a huge gain. But my point is that for such a simple solution it might be minuscule but in real projects it is definitely much more than this. 

    As always I have uploaded the complete working solution to DropBox.

    Until next time Happy Programming Smile

    Resources & further reading

    I would recommend following resources for learning more about design patterns:

    Gang of Four book on Design Patterns Elements of Reusable Object Oriented Software - http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612

    Do factory - http://www.dofactory.com/Patterns/Patterns.aspx

    Refactoring : Improving the design of existing code - http://www.amazon.com/Refactoring-Improving-Design-Existing-Code/dp/0201485672

    Refactoring to Patterns - http://industriallogic.com/xp/refactoring/ and the wonderful book http://www.amazon.com/Refactoring-Patterns-Joshua-Kerievsky/dp/0321213351

    Sunday, January 29, 2012

    My experience in building the First Windows Phone App

     

    Recently I published my first Windows Phone 7 application in the Marketplace. This app is named Singapore Public Holidays.I also adapted the same app to cater to the needs of my country of origin India and created an Indian version of the app which is called Indian Public Holidays. This post is about my experience in building the first Windows Phone 7 app.

    Why this app?

    Before I decided to developed the Singapore Public Holidays app, there were couple of other options that came to my mind. I thought of extending the NGTweet app which I had done as part of the Silverlight Learning Series. Another thought that came to my mind was to use some of the REST based public API’s and create some app with them. Something like Thought Of The Day service which can pull quotes from any of the public quotes services. Another thought was to build an app for some techie site like StackOverflow client for Windows Phone. All these ideas were either already implemented or were slightly complex. So I thought of building something which was very minimal in features and would not depend too much on external data. Also at the same time it had to be something useful. That’s when the idea of Singapore Public Holidays came to my mind.

    The holiday list for the year 2012 is published online by the Ministry of Manpower of Singapore. I decided to build a small app which would list these holidays. Instead of just showing the static date, I thought of displaying the number of days remaining from the current date would be interesting for users. As a user it would also be helpful if I can set the reminder for a holiday. So the reminder functionality was also added in the updated version.

    Just after I finished the first version of the app, Jesse Liberty suggested in his post published in MSDN magazine January 2012 Issue that “your first app should be interesting enough to be meaningful, yet simple enough to get underway”. I think my effort was inline with Jesse’s suggestions. Instead of spending weeks on developing an app I spend few hours of the day to get started. My intentions behind doing this was to understand the whole process of creating Windows Phone apps. I wanted to understand what all things are required to publish an app into the Marketplace and how long does it take for the complete process. Lets see how did I manage to do this.

    Different steps involved in developing and publishing the app

    First and foremost, we need the development environment to get started with building the intended application. Visual Studio 2010 was my preferred choice. Install the tools required for developing Windows Phone application using Visual Studio. The MSDN article about Create Your First Silverlight Application for Windows Phone is a good starting point.

    Apart from the standard Silverlight for Windows Phone features we might need additional features. I wanted to use features like ToggleButton which are not natively supported by Silverlight 5. So I downloaded the Windows Phone Toolkit which has additional controls. This is exactly same as the toolkit available for Silverlight.

    Once we have all the tools develop the application. This will take some time based on the complexity of the application. Once the application is developed we need to publish it to the central place where others can download it and install it on their Windows Phone devices. Marketplace is that central place which allows us to publish applications to the end users.

    Before we can submit an app, we need to register as a Windows Phone Developer at App hub. This costs $99 USD for annual subscription using which you can submit up to 100 apps. Once the account is created you are ready to go.

    The submission process is quite straightforward. You need to build the Silverlightapplication in Release mode and submit the .xap file along with the artwork. The artwork are a set of icons in different sizes which are used to represent the app in the Marketplace. These are also the icons which gets displayed on the Windows Phone device in the application list as well as on the home screen when the application is pinned to the start screen.

    Once the application is submitted, you’ll have to wait for the certification process to get completed. This can take long time depending on how big or small the application is. The testing is done on multiple Windows Phone devices from different vendors like Nokia, HTC, LG, Samsung etc. to make sure that the app confirms to all the requirements defined in the Application Certification Requirement.

    If everything goes fine, the application will be certified and you’ll be notified by email about the completion of the certification process. At the time of submitting the app to app hub, you can decide how should the app be published once it has passed the certification. I chose to automatically publish it but if you wish you can do it manually as well. The application submission walkthrough describes the whole process in more details.

     

    Things to remember

    When we do something for the first time there is always the tendency to forget something. Here are some of the things I missed out in my 3 submissions so far. Some of these things might be very silly but they can cause a delay of 1 week in publishing the app as the resubmission or an update goes through the same certification process.

    Icons and Screenshots

    The artwork required for marketplace is very important for the submission process. Make sure the size of the images is exactly the same as defined in the certification requirements document. The dimensions of the icons are clearly mentioned in the MSDN doc Application Submission Requirement. I had the agony of the app being rejected because I forgot to replace the default application icons.

    Also the screenshots needs to be taken with care. I forgot to to turn off the frame rate counters in the emulator and that was also highlighted in the rejection reasons. But this was not very consistent because one of the apps got approved when the screenshots had the frame rate counters displayed on them. I guess this depends on the vigilance of the tester testing the app.

    Choose the targeted market

    By default none of the supported markets are selected when we submit the app. We need to either choose all the supported markets for publishing our app or only the ones which we are interested in. If you forget to choose the target marketplace, the app might get certified but nobody will be able to download it.

    Be Patient

    The management interface for handling the published apps and also to check the status of submissions in app hub is bit slow. It takes hell lot of time to refresh. Even after the certification is completed it might take more than 48 hours for the app to actually appear on the marketplace for the users to download. I received emails about the successful completion of certification for my apps but had to wait for more than 2 days to download the apps.

    For the published apps we can get the statistics about the number of downloads, the crashes that has happened for users etc. Even this data is not available until a week or so after the app is published. On the whole this area seems to be very slow to react.

    Conclusion

    It is very easy to get started with the Windows Phone application development if you have prior experience in working with Silverlight. The complete process takes about 5-7 days to compete once the app is submitted until it is published in the Marketplace. There are not many apps available in the Windows phone Marketplace compared to iPhone or iPad. This might be an opportunity for people to develop interesting apps using the Silverlight technology which we are already aware of. If you don’t want to waste time in building native apps because you wish to build apps which can run on multiple platforms with minimal changes you can look at other options like offline HTML 5 apps. Thats a different topic altogether. But to get started with that approach you can look at PhoneGap which can be used to build native apps with web technologies.

    There is no code associated with this post, so don’t look for any download from dropbox Smile

    Until next time Happy Programming Smile

    Monday, January 23, 2012

    Rhino Mocks : Partially mock Internal method

    In my previous post on Partial Mocks, I had made a note that the method which we intend to partially mock has to be a public virtual method. Immediately after publishing the post, I came across a post by Matt Roberts which demonstrated how to use InternalsVisibleTo attribute to expose protected methods to certain assemblies. In this post I’ll demonstrate how to use InternalsVisibleTo attribute to unit test internal methods.

    What’s the problem with earlier approach?

    If we look at the code from the previous post, we had to make the methods public to be able to mock them using Rhino Mocks. In my opinion, this violates the encapsulation as we are forced to expose methods which are not really supposed to be public. We can overcome this by using the InternalsVisibleTo attribute. This attribute enables us to expose the types and methods which are defined as internal to certain assemblies only.

    Apply InternalsVisibleTo attribute

    We add the following two lines to the AssemblyInfo.cs of the main project file.

    [assembly: InternalsVisibleTo("PartialMocksExample.UnitTest")]

    [assembly: InternalsVisibleTo(RhinoMocks.NormalName)]

    We are going to access the methods from the UnitTest assembly. So the first line is understandable. The second line is bit confusing. This is required for exposing the internal methods to Rhino Mocks. Internally Rhino Mocks creates a proxy which intercepts the calls to the methods during mocking. Because of this reason we need to make our methods virtual so that the proxy can intercept these calls. Once we have added these lines, we can modify the access levels of the methods which need not be public. Here is the modified code for the CalculateDueAmount method

            internal virtual void CalculateTotalDueAmount(PhoneBill generateBill)

            {

                double totalDueAmount = generateBill.BilledAmount - generateBill.DiscountedAmount;

     

                generateBill.TotalDueAmount = Math.Round(totalDueAmount, ROUNDED_DIGITS, MidpointRounding.AwayFromZero);

            }

    Similarly I have modified the other methods as well from the previous post.

    Conclusion

    While following unit testing and TDD approach sometimes we are forced to violate some of the principles of encapsulation to satisfy the external tools like Rhino Mocks. Here we saw how we can make use of InternalsVisibleTo attribute to reduce the visibility of the method while testing. I agree that the methods we are mocking here are supposed to be private by default. We need to have a trade off between writing length unit tests or maintainable and more focussed tests. In my experience I have seen many TDD practitioners use internal methods to make use unit tests which are maintainable.

    As always the complete working solution is available for download at Dropbox.

    Until next time Happy Programming Smile

    Rhino Mocks : When to use Partial Mocks

    I have been using Rhino Mocks for past couple of years as the Dynamic mocking framework. It has support for different types of mocks like Strict mocks, Dynamic mocks and Partial mocks. The use of these types for specific use is bit confusing. Recently I had a wow moment when I found a real use of the Partial mock. This post is about that enlightenment.

    Most of the time I have relied on using Strict mock and stubs. As mentioned in the documentation of the Rhino mocks, my understanding of the partial mock was that it is used to mock the abstract classes and methods. But that's not the only use of Partial mock. It can be used to also test methods by mocking only the methods we are interested in. Lets dive into an example.

    How to use Partial Mocks

    Lets assume we are building a solution for calculating the phone bill  for a hypothetical phone company. As of now the company has two types of customers. The Normal ones and the Corporate customers. While calculating the total due amount for a customer, the phone company does not give any discount for the normal customers but corporate customers are eligible for the 25% discount on the billed amount. Here is an implementation

        public class PhoneBillCalculator

        {

            private const int ROUNDED_DIGITS = 2;

     

            private const double CORPORATE_DISCOUNT_PERCENTAGE = 0.25;

     

            public PhoneBill GenerateBill(Customer customer)

            {

                PhoneBill generateBill = new PhoneBill

                    {

                        CustomerType = customer.CustomerType,

                        BilledAmount = customer.BilledAmount

                    };

     

                if (customer.CustomerType == "Normal")

                {

                    generateBill.DiscountedAmount = 0;

                }

                else

                {

                    generateBill.DiscountedAmount = Math.Round(

                        customer.BilledAmount * CORPORATE_DISCOUNT_PERCENTAGE, ROUNDED_DIGITS, MidpointRounding.AwayFromZero);

                }

     

                double totalDueAmount = generateBill.BilledAmount - generateBill.DiscountedAmount;

     

                generateBill.TotalDueAmount = Math.Round(totalDueAmount, ROUNDED_DIGITS, MidpointRounding.AwayFromZero);

     

                return generateBill;

            }

        }

    Lets build a small set of tests to test these conditions.

        [TestClass]

        public class PhoneBillCalculatorTest

        {

            [TestMethod]

            public void GenerateBill_WithCustomerTypeAsNormal_ApplyNoDiscountOnTotalBilledAmount()

            {

                Customer customer = CreateCustomer("Normal", 170.50);

     

                PhoneBillCalculator billCalculator = new PhoneBillCalculator();

     

                PhoneBill phoneBill = billCalculator.GenerateBill(customer);

     

                Assert.IsNotNull(phoneBill);

                Assert.AreEqual("Normal", phoneBill.CustomerType);

                Assert.AreEqual(170.50, phoneBill.BilledAmount);

                Assert.AreEqual(0, phoneBill.DiscountedAmount);

                Assert.AreEqual(170.50, phoneBill.TotalDueAmount);

            }

     

            [TestMethod]

            public void GenerateBill_WithCustomerTypeAsCorporate_ApplyCorporateDiscountOnTotalBilledAmount()

            {

                Customer customer = CreateCustomer("Corporate", 170.50);

     

                PhoneBillCalculator billCalculator = new PhoneBillCalculator();

     

                PhoneBill phoneBill = billCalculator.GenerateBill(customer);

     

                Assert.IsNotNull(phoneBill);

                Assert.AreEqual("Corporate", phoneBill.CustomerType);

                Assert.AreEqual(170.50, phoneBill.BilledAmount);

                Assert.AreEqual(42.63, phoneBill.DiscountedAmount);

                Assert.AreEqual(127.87, phoneBill.TotalDueAmount);

            }

     

            private static Customer CreateCustomer(string customerType, double billedAmount)

            {

                return new Customer

                    {

                        CustomerType = customerType,

                        BilledAmount = billedAmount

                    };

            }

    There are two tests. The first one which tests that there is no discount applied for the Normal customer’s total due amount. And the second test validates that the customer is given his due 25% discount on the original billed amount. Both the tests are pretty straightforward. Because this post is related to Partial mocks, lets create a scenario which forces us to make use of Rhino mocks.

    Imagine there is an update to the original user requirement. The phone company has come up with more classifications for the customers. Based on various factors which are outside the scope of this post lets say the customers are classified as Normal, Corporate, Gold, Silver and Platinum. The discount varies for newly added types which are Gold, Silver and Platinum. Lets refactor the code to suite this requirement.

    In its current state, the GenerateBill method only works for Normal and Corporate customers. We can refactor the if else block into a switch case statement.  The first part which copies the values from customer to bill entity is common to all types of customers. It would be nice to refactor this into a separate method. Same is the case with the final part which computes the total due amount. Instead of going through step by step refactoring, I’ll directly show the final code snippet.

            public PhoneBill GenerateBill(Customer customer)

            {

                PhoneBill generateBill = GetGenerateBillWithDefaultValues(customer);

     

                CalculateDiscount(customer, generateBill);

     

                CalculateTotalDueAmount(generateBill);

     

                return generateBill;

            }

    After this refactoring, the GenerateBill method acts as template method which calls other methods. If we run the unit tests after this refactoring, they still run as expected. This ensures that we haven’t broken any of the existing functionality. There is one problem though. If we look at the tests they are testing the wrong thing. Observe carefully the data being setup in the test like the customer type and the billed amount. These values are not used in the GenerateBill method. We are setting data which is not in the scope of this method. If we follow TDD we should be testing only those things which are in the scope of the method under test. The existing unit tests are clearly violating this principle.

    Lets see how to fix this. The template method is calling the methods within the same class. These are not external dependencies which can be mocked using dynamic mocks. Rhino Mocks has a special mock which can be used for cases like this. Its called Partial Mock which allows us to selectively mock parts of the class. Go ahead and add reference to the latest version of Rhino Mocks. I used NuGet package manager to add the dependency to the project. Lets see how we can make use of it in the code.

            [TestMethod]

            public void GenerateBill_WithCustomer_GeneratesBill()

            {

                Customer customer = CreateCustomer("Normal", 170.50);

     

                PhoneBillCalculator billCalculator = CreatePhoneBillCalculator();

     

                PhoneBill expectedBill = new PhoneBill();

     

                billCalculator.Expect(x => x.GenerateBillWithDefaultValues(customer)).Return(expectedBill);

     

                billCalculator.Expect(x => x.CalculateDiscount(customer, expectedBill));

     

                billCalculator.Expect(x => x.CalculateTotalDueAmount(expectedBill));

     

                PhoneBill phoneBill = billCalculator.GenerateBill(customer);

     

                billCalculator.VerifyAllExpectations();

     

                Assert.IsNotNull(phoneBill);

            }

    We have set expectations on the instance of a PhoneBillCalculator itself. These methods are Then we exercised the method under test which is GenerateBill and finally we verify that the phone bill which is returned is not null. We also verify that all the expectations set on the bill calculator are met successfully. All this magic is possible because of the partial mock which is created in the helper method

            private PhoneBillCalculator CreatePhoneBillCalculator()

            {

                return MockRepository.GeneratePartialMock<PhoneBillCalculator>();

            }

    Note that we are not creating an instance of the PhoneBillCalculator class, instead we are generating a partial mock using the MockRepository. This gives us the flexibility of setting up expectations on the methods of PhoneBillCalculator class. Only prerequisite for using this approach is that the method we are going to set the expectation must be a public virtual method. Please refer to my other post to check how we can partially mock the internal methods using Rhino Mocks.

    Lets modify the earlier two tests to use the helper method instead of creating a new instance inside the test method.

                PhoneBillCalculator billCalculator = CreatePhoneBillCalculator();

    We can run all the unit tests now and see that all 3 tests are run successfully. How is that  possible? We modified the two tests to use the partial mock and did not set any expectations on the methods. Still the tests ran successfully. This is because if we don’t set any expectations on a partial mock, Rhino Mocks reverts to the actual implementation and executes the real code.

    With the refactored code, the scope of the earlier tests changes accordingly. I’ll leave it to the readers as an exercise to refactor those tests and also add new ones for the other pieces of the code which resulted as part of the refactoring. And by the way we did not add any code related to the discount for Gold, Silver and Platinum type of customers. Well that’s an exercise for you. You can add the required code to the switch statement.

    Conclusion

    Sometimes we need to mock some methods of the class which is under test. In general while unit testing we create a concrete instance of the class under test. We cannot set expectations on the methods of a concrete instance of a class. Under these circumstances we can make of PartialMocks provided by RhinoMocks to mock only few methods of a class. Those methods which are not mocked will be executed as normal.  This helps us in focusing on the methods under test and not to worry about the other methods which might be called internally. This can be helpful in building code which is more readable and maintainable. Small methods are always easier to maintain and test compared to the lengthy ones.

    Note : I have tried to followed Roy Osherove’s advice to make the unit tests more readable and maintainable. Roy’s post in 2006 MSDN magazine is worth a read.

    As always I have uploaded the complete working solution to Dropbox.

    Until next time happy programming Smile