Комментарии мертвы. Тесты живы

TL;DR: возьмите свой комментарий, сократите его и назовите свои функции. Теперь протестируйте его и удалите комментарии.

Устраненные проблемы

  • Ремонтопригодность
  • Читабельность

Связанные запахи кода







Шаги

  1. Возьмите комментарий метода, объясняющий, что делает функция.
  2. Переименуйте метод с описанием комментария (что).
  3. Создайте тесты для проверки комментариев.
  4. Опустите несущественные детали реализации.

Образец кода

До

def multiply(a, b):
    # This function multiplies two numbers and returns the result
    # If one of the numbers is zero, the result will be zero
    # If the number are both positive, the result will be positive
    # If the number are both negative, the result will be positive
    # The multiplication is done by invoking a primitive
    return a * b

# This code has a comment that explains what the function does.
# Instead of relying on this comment to understand the behavior of the code,
# we can write some unit tests that verify the behavior of the function.

После

def multiply(first_multiplier, second_multiplier):
    return first_multiplier * second_multiplier

class TestMultiply(unittest.TestCase):
    def test_multiply_both_possitive_outcome_is_possitive(self):
        result = multiply(2, 3)
        self.assertEqual(result, 6)
    def test_multiply_both_negative_outcome_is_positive(self):
        result = multiply(-2, -4)
        self.assertEqual(result, 8)
    def test_multiply_first_is_zero_outcome_is_zero(self):
        result = multiply(0, -4)
        self.assertEqual(result, 0)
    def test_multiply_second_is_zero_outcome_is_zero(self):
        result = multiply(3, 0)
        self.assertEqual(result, 0)
    def test_multiply_both_are_zero_outcome_is_zero(self):
        result = multiply(0, 0)
        self.assertEqual(result, 0)           

# We define a test function called test_multiply,
# which calls the multiply function with different arguments 
# and verifies that the result is correct using the assertEqual method.

# 1. Take the comment of the method explaining what the function does.
# 2. Rename the method with the comment description (the what).
# 3. Create tests to verify the comments. 
# 4. Omit irrelevant implementation details

Тип

[X] Полуавтоматический

Мы можем переписать комментарий и сжать его, но это не всегда алгоритмически.

Безопасность

Это не безопасный рефакторинг, но он увеличивает покрытие.

Почему код лучше?

Комментарии врут. Код не работает.

Ограничения

Мы не можем тестировать приватные методы.

В маловероятном случае, когда нам нужно заменить комментарий к приватному методу, мы должны протестировать его косвенно или извлечь в другой объект.

Мы можем оставлять комментарии, отражающие важные дизайнерские решения.

Теги

  • Комментарии

Связанные рефакторинги



Кредиты

Изображение пользователя philm1310 на Pixabay

Эта статья является частью серии статей о рефакторинге.