Refactor and Improve the Code

Learn to refactor and improve the code in test-driven development.

This isn’t a required step because not all code necessarily needs to be refactored. However, when there is a need to improve the code without changing the underlying functionality, we can refactor the code. This process goes hand in hand with the test written in the first step because while refactoring the code, we make sure that we still have a passing test.

How does it work?

Refactoring helps remove duplicates. When refactoring, we can either work on the code or on the tests. However, it’s recommended not to work on both simultaneously. This helps avoid complicating the refactoring process.

Refactor the test

As an example, let’s try to refactor this test method:

class UserProfile(TestCase):
    def test_create_user_profile(self):
        self.profile = Profile.objects.create(
            first_name = 'Samuel',       
            last_name = 'Torimiro',
        )

        self.assertEqual(f'{self.profile.first_name}', 'Samuel')
        self.assertEqual(f'{self.profile.last_name}', 'Torimiro')

In addition to the previous test. Let us refactor by adding an assertion, to test that the string representation of the model returns the required output.

from django.test import TestCase

from .models import Profile

class UserProfile(TestCase):
    def test_create_user_profile(self):
        self.profile = Profile.objects.create(
            first_name = 'Samuel',       
            last_name = 'Torimiro',
        )

        self.assertEqual(f'{self.profile.first_name}', 'Samuel')
        self.assertEqual(f'{self.profile.last_name}', 'Torimiro')
        self.assertEqual(str(self.profile), 'Samuel') # new

After refactoring, we must rerun the test to make sure it still passes.

Refactor the code

In addition, we can also refactor the code. Let’s take a look at an example.

The models.py file

from django.db import models

# Create your models here.

class Profile(models.Model):

    first_name = models.CharField(max_length=255, help_text='Enter your first name')
    last_name = models.CharField(max_length=255, help_text='Enter your last name')

    def __str__(self):
        return self.first_name

Here, we include a help_text attribute for both the first_name and last_name fields. This can be quite useful to make forms readable to users on the HTML page since it appends this text to the bottom of the input field.

Note: Refactoring isn’t compulsory. However, we can refactor our code to make it more refined when necessary.

Get hands-on with 1200+ tech skills courses.