Chapter 2. A Test Driven Development Example in Rust

 

This is an example of how to work through the Prime Factors Kata using Test Driven Development. The kata, as we’re going to interpret it, is:

Write a function that takes an integer greater than 1 and returns a vector of its prime factors, which are the prime numbers that divide that integer exactly, in ascending order. For example, the prime factors of 12 are 2, 2, 3.

I mentioned earlier that there are two types of objects: services and other objects. The second type of objects can be divided into more specific subtypes, namely value objects and entities (sometimes known as “models”). Services will create or retrieve entities, manipulate them, or pass them on to other services. They will also create value objects and pass them on as method arguments, or create modified copies of them. In this sense, entities and value objects are the materials that services use to perform their tasks.

Test Driven Development (TDD) is a software development method where you repeat these three steps:

  1. Red: Write a failing test.
  2. Green: Write just enough code to make the test pass.
  3. Refactor: Keeping the tests green, improve the code as much as you can.

These steps enable you to explore the design space of a solution guided by the constraints of getting and keeping the test cases passing. Let’s see what Test Driven Development feels like in Rust by implementing a program to find the prime factors of a number.

sitemap