This is a minor point, but would it make more sense to re-arrange this logic so that the average is only computed if needed?