Refactor code to remove duplicate logic