Refactor to remove duplicated code