Factor out a chunk of code into a function