Minor refactoring to put duplicated code into a function