Type refinement and code rearrangement