Volume Calculator

A TDD practice exercise suggested by Jason Gorman in his book on the subject - Codemanship - TDD.

Instructions

Writing the assertions first and working backwards to the set-up, test-drive some code to calculate how much water will be needed to to fill the following:

  1. A cube
  2. A cylinder
  3. A pyramid

Notes before test-driving the code

To calculate the volume of any solid, there are two steps required:

  1. Calculate the volume in cubic cm - cm3.
  2. Convert the volume in cm3 to litres.

Cube

The formula for calculating the volume of a cube in cm3 is L x W x H:

10cm x 10cm x 10cm = 1000cm3

1 litre is equal to 1000cm3. Therefore to calculate the volume of water needed to fill the cube in litres, you can simply divide the cm3 volume by 1000:

1000cm3 / 1000 = 1 litre.

Cylinder

The formula for calculating the volume of a cylinder is π x r2 x H:

π x 10cm2 x 10cm

which is also:

π x 100cm x 10cm = 3141.59cm3

Therefore the volume of this cylinder is 3141.59cm3 / 1000 = 3.14 litres

Pyramid

The formula for calculating the volume of a pyramid is 1/3 x L x W x H:

1/3 x 10cm3 x 10cm3 10cm3 = 333.33cm3

Therefore the volume of this pyramid is 333.33cm3 / 1000 = 0.33 litres

Pre-TDD thoughts

It would be good to separate the calculation of the area of the solid first, perhaps with a Solid interface:

interface Solid {
  getAreaInCubicCentimetres(): number;
}

And then the class can implement this interface. For example a cube:

class Cube implements Solid {
  #length: number;
  #width: number;
  #height: number;

  constructor(length: number, width: number, height: number) {
    this.#length = length;
    this.#width = width;
    this.#height = height;
  }

  get length(): number {
    return this.#length;
  }

  get width(): number {
    return this.#width;
  }

  get height(): number {
    return this.#height;
  }

  getAreaInCubicCentimetres(): number {
    return this.length * this.width * this.height;
  }
}

Following this, a class called VolumeCalculator can accept a solid class to retrieve its area:

class VolumeCalculator {
  getRequiredLitresOfWater(solid: Solid): number {
    return solid.getAreaInCubicCentimetres() / 1000;
  }
}

const cube = new Cube(10, 10, 10);

const volumeCalculator = new VolumeCalculator();

const litres = volumeCalculator.getRequiredLitresOfWater(cube);

Something along these lines.