Clean up by extracting commonly used code as a function.