Refactor some duplicated code