Refactor common code into functions