Refactor the save function