Move duplicate code to a function