Refactor the code to avoid duplication and separate concerns