Refactored code with a function