Refactor duplicated logic