OdeToCode IC Logo

The Composition Kata

Friday, February 15, 2013

The Kata repository has new additions.

The Refactoring kata I pushed out last year now has a Java version available (thanks, Tom!).

Related to the previous post, I also added a Composition Kata.  Excerpt from the README:

One day a developer was writing some logic to perform calculations on a collection of Measurement objects with X and Y properties. The developer knew the business would need different types of aggregations performed on the collection (sometimes a simple sum, sometimes an average), and the business would also want to filter measures (sometimes removing low values, sometimes removing high values).

The developer wanted to make sure all algorithms for calculating a result would filter a collection of measurements before aggregation. After consulting with a book on design patterns, the developer decided the Template Method pattern would be
ideal for enforcing a certain ordering on operations while still allowing subclasses to override and change the actual filtering and the calculations.

public abstract class PointsAggregator
    protected PointsAggregator(IEnumerable<Measurement> measurements)
        Measurements = measurements;

    public virtual Measurement Aggregate()
        var measurements = Measurements;
        measurements = FilterMeasurements(measurements);
        return AggregateMeasurements(measurements);

    protected abstract IEnumerable<Measurement> FilterMeasurements(IEnumerable<Measurement> measurements);
    protected abstract Measurement AggregateMeasurements(IEnumerable<Measurement> measurements);
    protected readonly IEnumerable<Measurement> Measurements;

From this base class the developer started creating different classes to represent different calculations (along with unit tests).

Your job is to create a new calculation. A calculation to filter out measurements with low values and then sum the X and Y values of the remaining measurements. You'll find details in the comments of the code, and the unit tests.

You'll implement the calculation twice. Once by building on top of the Template Method approach (in the Inheritance folder), and once with a compositional approach (in the Composition folder).  When you are finished and all of the tests pass (9 total, you'll start with 6), take some time to reflect on the different approaches.

- Which are the drawbacks and benefits to each?
- Which one would you rather build on in the future?