Improve robustness and extract common code