refactor some duplicated logic.