Refactor code to remove duplication.
Add unit tests.