Refactor duplicated code.

No intended functionality change.