Refactor code to remove duplication