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

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020