Reorder while conditions to allow short-circuit, preventing index out of bounds exception