Refactor duplicate code