Refactoring distance calculation