Refactor some common code into a function.