Move common code into functions