Move duplicated code into a helper function.