Home > Articles > Programming > C#

  • Print
  • + Share This
This chapter is from the book

Implementation

We can't get very far with the payroll window without being able to add transactions, so we'll start with the form to add an employee transaction, shown in Figure 38-2. Let's think about the business rules that have to be achieved through this window. We need to collect all the information to create a transaction. This can be achieved as the user fills out the form. Based on the information, we need to figure out what type of AddEmployeeTransaction to create and then put that transaction in the list to be processed later. This will all be triggered by a click of the Submit button.

That about covers it for the business rules, but we need other behaviors to make the UI more usable. The Submit button, for example, should remain disabled until all the required information is supplied. Also, the text box for hourly rate should be disabled unless the Hourly radio button is on. Likewise, the Salary, Base Salary, and Commission text boxes should remain disabled until the appropriate radio button is clicked.

We must be careful to separate the business behavior from the UI behavior. To do so, we'll use the MODEL VIEW PRESENTER design pattern. Figure 38-3 shows a UML design for how we'll use MODEL VIEW PRESENTER for our current task. You can see that the design has three components: the model, the view, and the presenter. The model in this case represents the AddEmployeeTransaction class and its derivatives. The view is a Windows Form called AddEmployeeWindow, shown in Figure 38-2. The presenter, a class called AddEmployeePresenter, glues the UI to the model. AddEmployeePresenter contains all the business logic for this particular part of the application, whereas AddEmployeeWindow contains none. Instead, AddEmployeeWindow confines itself to the UI behavior, delegating all the business decisions to the presenter.

Figure 38-1

Figure 38-3 MODEL VIEW PRESENTER pattern for adding an employee transaction

An alternative to using MODEL VIEW PRESENTER is to push all the business logic into the Windows Form. In fact, this approach is very common but quite problematic. When the business rules are embedded in the UI code, not only do you have an SRP violation, but also the business rules are much more difficult to automatically test. Such tests would have to involve clicking buttons, reading labels, selecting items in a combo box, and fidgeting with other types of controls. In other words, in order to test the business rules, we'd have to actually use the UI. Tests that use the UI are fragile because minor changes to the UI controls have a large impact on the tests. They're also tricky because getting UIs in a test harness is a challenge in and of itself. Also, later down the road, we may decide that a Web interface is needed, and business logic embedded in the Windows form code would have to be duplicated in the ASP.NET code.

The observant reader will have noticed that the AddEmployeePresenter does not directly depend on the AddEmployeeWindow. The AddEmployeeView interface inverts the dependency. Why? Most simply, to make testing easier. Getting user interfaces under test is challenging. If AddEmployeePresenter was directly dependent upon AddEmployeeWindow, AddEmployeePresenterTest would also have to depend on AddEmployeeWindow, and that would be unfortunate. Using the interface and MockAddEmployeeView greatly simplifies testing.

Listing 38-1 and Listing 38-2 show the AddEmployeePresenterTest and AddEmployeePresenter, respectively. This is where the story begins.

Listing 38-1. AddEmployeePresenterTest.cs

using NUnit.Framework;
using Payroll;

namespace PayrollUI
{
  [TestFixture]
  public class AddEmployeePresenterTest
  {
    private AddEmployeePresenter presenter;
    private TransactionContainer container;
    private InMemoryPayrollDatabase database;
    private MockAddEmployeeView view;

    [SetUp]
    public void SetUp()
    {
      view = new MockAddEmployeeView();
      container = new TransactionContainer(null);
      database = new InMemoryPayrollDatabase();
      presenter = new AddEmployeePresenter(
        view, container, database);
    }

    [Test]
    public void Creation()
    {
      Assert.AreSame(container,
        presenter.TransactionContainer);
    }

    [Test]
    public void AllInfoIsCollected()
    {
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.EmpId = 1;
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.Name = "Bill";
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.Address = "123 abc";
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.IsHourly = true;
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.HourlyRate = 1.23;
      Assert.IsTrue(presenter.AllInformationIsCollected());

      presenter.IsHourly = false;
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.IsSalary = true;
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.Salary = 1234;
      Assert.IsTrue(presenter.AllInformationIsCollected());

      presenter.IsSalary = false;
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.IsCommission = true;
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.CommissionSalary = 123;
      Assert.IsFalse(presenter.AllInformationIsCollected());
      presenter.Commission = 12;
      Assert.IsTrue(presenter.AllInformationIsCollected());
    }

    [Test]
    public void ViewGetsUpdated()
    {
      presenter.EmpId = 1;
      CheckSubmitEnabled(false, 1);

      presenter.Name = "Bill";
      CheckSubmitEnabled(false, 2);

      presenter.Address = "123 abc";
      CheckSubmitEnabled(false, 3);

      presenter.IsHourly = true;
      CheckSubmitEnabled(false, 4);

      presenter.HourlyRate = 1.23;
      CheckSubmitEnabled(true, 5);
    }
    private void CheckSubmitEnabled(bool expected, int count)
    {
      Assert.AreEqual(expected, view.submitEnabled);
      Assert.AreEqual(count, view.submitEnabledCount);
      view.submitEnabled = false;
    }

    [Test]
    public void CreatingTransaction()
    {
      presenter.EmpId = 123;
      presenter.Name = "Joe";
      presenter.Address = "314 Elm";

      presenter.IsHourly = true;
      presenter.HourlyRate = 10;
      Assert.IsTrue(presenter.CreateTransaction()
        is AddHourlyEmployee);

      presenter.IsHourly = false;
      presenter.IsSalary = true;
      presenter.Salary = 3000;
      Assert.IsTrue(presenter.CreateTransaction()
        is AddSalariedEmployee);

      presenter.IsSalary = false;
      presenter.IsCommission = true;
      presenter.CommissionSalary = 1000;
      presenter.Commission = 25;
      Assert.IsTrue(presenter.CreateTransaction()
        is AddCommissionedEmployee);
    }

    [Test]
    public void AddEmployee()
    {
      presenter.EmpId = 123;
      presenter.Name = "Joe";
      presenter.Address = "314 Elm";
      presenter.IsHourly = true;
      presenter.HourlyRate = 25;

      presenter.AddEmployee();

      Assert.AreEqual(1, container.Transactions.Count);
      Assert.IsTrue(container.Transactions[0]
        is AddHourlyEmployee);
    }
  }
}

Listing 38-2. AddEmployeePresenter.cs

  using Payroll;

  namespace PayrollUI
  {
    public class AddEmployeePresenter
    {
      private TransactionContainer transactionContainer;
      private AddEmployeeView view;
      private PayrollDatabase database;

      private int empId;
      private string name;
      private string address;
      private bool isHourly;
      private double hourlyRate;
      private bool isSalary;
      private double salary;
      private bool isCommission;
      private double commissionSalary;
      private double commission;

      public AddEmployeePresenter(AddEmployeeView view,
        TransactionContainer container,
        PayrollDatabase database)
      {
        this.view = view;
        this.transactionContainer = container;
        this.database = database;
      }

      public int EmpId
      {
        get { return empId; }
        set
        {
          empId = value;
          UpdateView();
        }
      }

      public string Name
      {
        get { return name; }
        set
        {
          name = value;
          UpdateView();
        }
      }

      public string Address
      {
        get { return address; }


        set
        {
          address = value;
          UpdateView();
        }
      }

      public bool IsHourly
      {
        get { return isHourly; }
        set
        {
          isHourly = value;
          UpdateView();
        }
      }

      public double HourlyRate
      {
        get { return hourlyRate; }
        set
        {
          hourlyRate = value;
          UpdateView();
        }
      }

      public bool IsSalary
      {
        get { return isSalary; }
        set
        {
          isSalary = value;
          UpdateView();
        }
      }

      public double Salary
      {
        get { return salary; }
        set
        {
          salary = value;
          UpdateView();
        }
      }

      public bool IsCommission
      {
        get { return isCommission; }
        set
        {
          isCommission = value;
          UpdateView();
        }


      }

      public double CommissionSalary
      {
        get { return commissionSalary; }
        set
        {
          commissionSalary = value;
          UpdateView();
        }
      }

      public double Commission
      {
        get { return commission; }
        set
        {
          commission = value;
          UpdateView();
        }
      }

      private void UpdateView()
      {
        if(AllInformationIsCollected())
          view.SubmitEnabled = true;
        else
          view.SubmitEnabled = false;
      }

      public bool AllInformationIsCollected()
      {
        bool result = true;
        result &= empId > 0;
        result &= name != null && name.Length > 0;
        result &= address != null && address.Length > 0;
        result &= isHourly || isSalary || isCommission;
        if(isHourly)
          result &= hourlyRate > 0;
        else if(isSalary)
          result &= salary > 0;
        else if(isCommission)
        {
          result &= commission > 0;
          result &= commissionSalary > 0;
        }
        return result;
      }

      public TransactionContainer TransactionContainer
      {
        get { return transactionContainer; }
      }

      public virtual void AddEmployee()
      {
        transactionContainer.Add(CreateTransaction());
      }

      public Transaction CreateTransaction()
      {
        if(isHourly)
          return new AddHourlyEmployee(
            empId, name, address, hourlyRate, database);
        else if(isSalary)
          return new AddSalariedEmployee(
            empId, name, address, salary, database);
        else
          return new AddCommissionedEmployee(
            empId, name, address, commissionSalary,
            commission, database);
      }
   }
}

Starting with the SetUp method of the test, we see what's involved in instantiating the AddEmployeePresenter. It takes three parameters. The first is an AddEmployeeView, for which we use a MockAddEmployeeView in the test. The second is a TransactionContainer so that it has a place to put the AddEmployeeTransaction that it will create. The last parameter is a PayrollDatabase instance that won't be used directly but is needed as a parameter to the AddEmployeeTransaction constructors.

The first test, Creation, is almost embarrassingly silly. When first sitting down to write code, it can be difficult to figure out what to test first. It often helps to test the simplest thing you can think of. Doing so gets the ball rolling, and subsequent tests come much more naturally. The Creation test is an artifact of this practice. It makes sure that the container parameter was saved, and it could probably be deleted at this point.

The next test, AllInfoIsCollected, is much more interesting. One of the responsibilities of the AddEmployeePresenter is to collect all the information required to create a transaction. Partial data won't do, so the presenter has to know when all the necessary data has been collected. This test says that the presenter needs a methods called AllInformationIsCollected, that returns a boolean value. The test also demonstrates how the presenter's data is entered through properties. Each piece of data is entered here one by one. At each step, the presenter is asked whether it has all the data it needs and asserts the expected response. In AddEmployeePresenter, we can see that each property simply stores the value in a field. AllInformationIsCollected does a bit of Boolean algebra as it checks that each field has been provided.

When the presenter has all the information it needs, the user may submit the data adding the transaction. But not until the presenter is content with the data provided should the user be able to submit the form. So it is the presenter's responsibility to inform the user when the form can be submitted. This is tested by the method ViewGetsUpdated. This test provides data, one piece at a time to the presenter. Each time, the test checks to make sure that the presenter properly informs the view whether submission should be enabled.

Looking in the presenter, we can see that each property makes a call to UpdateView, which in turn calls the SaveEnabled property on the view. Listing 38-3 shows the AddEmployeeView interface with SubmitEnabled declared. AddEmployeePresenter informs that submitting should be enabled by calling the SubmitEnabled property. Now we don't particularly care what SubmitEnabled does at this point. We simply want to make sure that it is called with the right value. This is where the AddEmployeeView interface comes in handy. It allows us to create a mock view to make testing easier. In MockAddEmployeeView, shown in Listing 38-4, there are two fields: submitEnabled, which records the last values passed in, and submitEnabledCount, which keeps track of how many times SubmitEnabled is invoked. These trivial fields make the test a breeze to write. All the test has to do is check the submitEnabled field to make sure that the presenter called the SubmitEnabled property with the right value and check submitEnabledCount to make sure that it was invoked the correct number of times. Imagine how awkward the test would have been if we had to dig into forms and window controls.

Listing 38-3. AddEmployeeView.cs

namespace PayrollUI
{
  public interface AddEmployeeView
  {
    bool SubmitEnabled { set; }
  }
}

Listing 38-4. MockAddEmployeeView.xs

namespace PayrollUI
{
  public class MockAddEmployeeView : AddEmployeeView
  {
    public bool submitEnabled;
    public int submitEnabledCount;

    public bool SubmitEnabled
    {
      set
      {
        submitEnabled = value;
        submitEnabledCount++;
      }
    }
  }
}

Something interesting happened in this test. We were careful to test how AddEmployeePresenter behaves when data is entered into the view rather than testing what happens when data is entered. In production, when all the data is entered, the Submit button will become enabled. We could have tested that; instead, we tested how the presenter behaves. We tested that when all the data is entered, the presenter will send a message to the view, telling it to enable submission.

This style of testing is called behavior-driven development. The idea is that you should not think of tests as tests, where you make assertions about state and results. Instead, you should think of tests as specifications of behavior, in which you describe how the code is supposed to behave.

The next test, CreatingTransaction, demonstrates that AddEmployeePresenter creates the proper transaction, based on the data provided. AddEmployeePresenter uses an if/else statement, based on the payment type, to figure out which type of transaction to create.

That leaves one more test, AddEmployee. When the all the data is collected and the transaction is created, the presenter must save the transaction in the TransactionContainer so that it can be used later. This test makes sure that this happens.

With AddEmployeePresenter implemented, we have all the business rules in place to create AddEmployeeTransactions. Now all we need is user interface.

  • + Share This
  • 🔖 Save To Your Account