Factor out some duplicate code