replace repeating code with a generic function