Factor out code to a function