Null Object Refactoring
page 3 of 5
by Brian Mains
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 27828/ 95

A Factory Example

As another example I have a CityFactory class, which returns an array of City objects.  However, the business class will default to the NullCity implementation if no value has been provided yet.  So, the City definition has properties of ID and Name.

Listing 5

public class City
{
  private int _id;
  private string _name;
  public int ID
  {
    get
    {
      return _id;
    }
  }
  public string Name
  {
    get
    {
      return _name;
    }
  }
}

The NullCity defaults the ID to -1 and the Name to empty through the NullCity constructor (using the technique for nullable objects above, not because of the default values of City).  The following is a NUnit test that shows the flow in the application, as city defaults to a null value, and then gets populated from the factory later.

Listing 6

[Test]
public void TestCity()
{
  City city = NullCity.Empty();
  Assert.AreEqual( - 1, city.ID);
  Assert.AreEqual(string.Empty, city.Name);
  city = CityFactory.GetCities()[0];
  Assert.AreEqual(1, city.ID);
  Assert.AreEqual("Pittsburgh", city.Name);
}

The test runs successfully. The code is available with a unit test to illustrate the process and it can be downloaded from the URL given in the download section.


View Entire Article

User Comments

Title: good write-up   
Name: HoyaSaxa93
Date: 2007-05-15 3:26:44 PM
Comment:
good examples of factoring / backing into null objects






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2020 ASPAlliance.com  |  Page Processed at 2020-07-04 9:08:40 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search