Combine Parameters

 

Yesterday we discovered how creating internal structure in a class makes it easier to understand its behaviour.

The example we used was a highly parameterised constructor for a Customer class, with eight parameters. We stored each parameter in a separate property (or member variable, if you prefer). That was the original state.

However, the parameters belonged to logical groupings, and we created classes for these: CustomerDetails, CustomerAddress and CustomerLoyalty. We then instantiated these classes inside the Customer constructor and assigned the references to appropriate Customer properties (or class members):

  public Customer(string firstName, string lastName, int age,
                  string streetAddress, string townOrCity, Country country,
                  int loyaltyPoints, int loyaltyScore)
  {
     Details = new CustomerDetails(firstName, lastName, age);
     Address = new CustomerAddress(streetAddress, townOrCity, country);
     Loyalty = new CustomerLoyalty(loyaltyPoints, loyaltyScore);
  }

Yes, definitely an improvement over setting and storing individual properties.

However, is this the end of the line? Or can we do better still?

Given that sets of the parameters belong together, i.e. they are cohesive, we could ask why we pass them individually into the Customer constructor in the first place. It would make sense then if they travelled as a group even before they encounter, and then become part of, the Customer class.

Yes, sure.

Let’s change the Customer constructor accordingly:

  public Customer(CustomerDetails details,
                  CustomerAddress address,
                  CustomerLoyalty loyalty)
  {
     Details = details;
     Address = address;
     Loyalty = loyalty;
  }

Tidy.

The cool thing is that behaviour that might easily have found its way into the Customer class when it lacked internal structure can now be offloaded onto these other component classes. For example, calculating a customer’s Net Promoter Score (NPS) could be delegated to the CustomerLoyalty class, thus reducing the required logic, and associated complexity, of Customer.

Consider combining parameters into cohesive objects.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply