Pattern Matching to the Rescue

Today I was pair programming with a colleague to add some new functionality to an existing, and slightly gnarly, codebase.  Whilst there we a found an existing class which we should reuse, if only it wasn’t so tightly coupled to another object.

It’s purpose was to filter out a lost of parent objects by a value in a child object. It would loop through the whole list of parents examining each child. We wanted to reuse the class, but we were only handling the child objects and creating a bunch of parent objects for this purpose would be incredibly wrong. We needed to refactor to decouple, but how?

IList filteredParents = _filter.FindMatch(parents);

Suddenly, a light bulb goes off in my colleague’s eyes and he proceeds to turn the problem on its head – pattern matching.

We refactored the filter class so that it accepted a single child object and returned a bool indicating whether the match was successful. Then, using Linq we applied this pattern to the list of parent objects to filter out those with matching children. It was beautiful.

IList filteredParents = parents.Where(x => _filter.FindMatch(x.Child));

We can now reuse the filter class on our list of child objects without a need for the parents.

I realise that this is normal practice in the functional world, and I’ve toyed with it before, so I’m disappointed that I didn’t figure this out sooner, but it’s amazingly simple when put into action.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s