move duplicated code to a function