23.2. Examining the Factory Pattern

Chapter 2 touched on the point that unit tests aren't strictly supposed to go outside of their class boundary because a unit is the smallest testable item. Consider the following abridged pseudo code snippet:

Public Class AccountProvider
{
    Public AccountData CreateNewAccount( Username, Password, ... )
    {
         AccountData account = new AccountData();
         CryptographyProvider crypto = new CryptographyProvider();
         AccountDataAccess dataAccess = new AccountDataAccess();

         // compile account data object
         account.Username = Username;
         account.Password = crypto.Encrypt( Encrypt.OneWay, Password );
         ...

         // create new account
         dataAccess.CreateNewAccount( account );

    }

}

The example is used for discussion purposes only. You can see that the code creates a number of objects to perform its core processing. You can also see that the CreateNewAccount method doesn't include any diagnostic code, either. However, if you followed the rule that unit testing must not go outside its class boundary, you'd have to stub all the components the CreateNewAccount method was calling. I'll discuss whether there is any actual value of doing this later. For the moment, let's simply look at how the creation of both test and real objects could be done to ease testing. There are many ways of doing this, including:

  • Using conditional compilation to determine the "type" of component to be instantiated.

  • Implementing software factories to return the right "type" of component, which can also be based ...

Get Design – Build – Run: Applied Practices and Principles for Production-Ready Software Development now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.