refactor duplicated code in utility function