[SPARK-3944][Core] Code re-factored as suggested