Last week my pair and I came up with an elegant solution to a problem that could have seriously bloated an already busy class.
The class was called Matcher and part of its job is to Match a Person to a Contact (the objects represent models from 2 different systems) with the method isMatch. The rules for matching were to first check that the full names were the same and, if they were, then check to see if either the email addresses match or one of the 6 phone fields. If only the names matched the method should return false.
The class was called Matcher and part of its job is to Match a Person to a Contact (the objects represent models from 2 different systems) with the method isMatch. The rules for matching were to first check that the full names were the same and, if they were, then check to see if either the email addresses match or one of the 6 phone fields. If only the names matched the method should return false.
The problem itself isn't very hard, but looking at the rest of the class I did not want to clutter this method up with a bunch of if-then-else statements and, more importantly, I wanted the code to be readable.
Looking at both Contact and Person, my pair and I noticed that they both had similar attributes (first name, last name, email address, day phone, etc), however, the field names were slightly different. Our approach was to use the Adapter Pattern to change Contact and Person into MatchableContacts. MatchableContact would have a method match() which would take in a MatchableContact and would return a Boolean based on the Names AND (Email Addresses OR Day Phones OR Evening Phones OR etc...)What this did was turn 50 lines of code in isMatch() to 3 lines and made the code significantly more readable. Instead of if-then-else we had:
MatchableContact matchable1 = MatchableContact.getInstance(person);
matchableContact matchable2 = MatchableContact.getInstance(contact);
return matchable1.match(matchable2);
And the match method looked like this:
return this.getFullName.equals(matchableContact.getFullName) && (this.getEmail.equalsIgnoreCase(matchableContact.getEmail) || etc...)
As an added bonus my pair realized that he could now re-use our new MatchableContact class for a problem that he had been working on for the past 2 days!
2 comments:
I like that. Very clean. Less is more!
Nice application of the Adapter Design Pattern. Thanks for sharing.
Post a Comment