factorize compute_distance method