Programming Search⌘K

Taskintro

Define a class

Also called declare a class, write a class, class definition, class declaration, struct with methods, user-defined type.

Define a Rectangle class with two fields, a constructor and methods, then make an instance, call its methods and change its state.

Task

Define a class Rectangle with two fields, width and height, a constructor that sets them, and three methods: area(), perimeter() and scale(factor), which multiplies both sides by factor and so changes the instance. Then use it. The function rectangle_report(width, height, factor) makes one rectangle, reads its area and perimeter, scales it, and reads them again. It returns the four numbers. For example, rectangle_report(3, 4, 2) is [12, 14, 48, 28].

The sides and the factor are 0 or more, and the area after the scale fits in a signed 32-bit integer. The tests also check that two instances have their own fields: a call to scale on one does not change the other.

Solutions

Language The type The constructor The methods
Python class Rectangle __init__(self, width, height) functions in the class body, with self first
JavaScript class Rectangle constructor(width, height) methods in the class body; this is the instance
TypeScript class Rectangle with typed fields constructor(width: number, height: number) as in JavaScript, with types
Java final class Rectangle with private fields Rectangle(int width, int height) instance methods
C# sealed class Rectangle with properties Rectangle(int width, int height) instance methods
C++ class Rectangle with private members a constructor with a member initializer list member functions; const for the ones that only read
Go type Rectangle struct the function New methods with a value or a pointer receiver
Rust struct Rectangle the associated function new methods in an impl block with &self or &mut self
C struct rectangle the function rectangle_make functions that take a pointer to the struct
  • The class body holds the fields and the methods. In Python, "When a class defines an init() method, class instantiation automatically invokes init() for the newly created class instance."1 The arguments of the call Rectangle(3, 4) go to __init__, and __init__ sets the fields on self. A JavaScript class body is where "you define class members, such as methods or constructor"2, and new Rectangle(3, 4) calls the constructor. TypeScript adds a type to each field, and its setting strictPropertyInitialization "controls whether class fields need to be initialized in the constructor".3
  • Java and C# keep the fields private. The Java solution has private fields and methods that read them. If a Java class declares no constructor, "a default constructor is implicitly declared"4, which takes no arguments, so the fields keep their default values until something sets them. In C#, "A class is a reference type that defines a blueprint for objects."5 The C# solution uses properties with a private set, so other code can read Width and only the class can change it. C# also has primary constructors, which "add parameters directly to the class declaration"5, for example class Rectangle(int width, int height).
  • C++ marks the methods that only read. "A class is a user-defined type."6 The const after the parameter list of area() tells the compiler that the method does not change the object, so it can be called on a const Rectangle. The short methods are in the class body, and scale is defined in the .cpp file as Rectangle::scale.
  • Go and Rust have no classes. A struct holds the fields, and the methods are declared outside it. In Go, "A receiver base type cannot be a pointer or interface type and it must be declared in the same package as the method."7 Area has a value receiver and reads a copy; Scale has a pointer receiver, *Rectangle, because it changes the rectangle. Neither language has constructors: Go uses a function New, and Rust uses an associated function with the conventional name new. In Rust, "Within an impl block, the type Self is an alias for the type that the impl block is for."8 &self borrows the rectangle to read it, and &mut self borrows it to change it. The Rust sides are u32, so a negative side cannot be made.
  • C writes the pattern by hand. A struct holds the fields, and each "method" is a function whose first parameter is a pointer to the struct. A const struct rectangle * parameter marks a function that only reads. C has no access control, so any code can change r.width.

Alternatives

  • A record. When the fields never change after construction, a Java record Rectangle(int width, int height), a C# record, a Python @dataclass(frozen=True) or a Kotlin data class writes the constructor, the accessors, equality and the text form for you. Then scale returns another rectangle and leaves the first one as it was.
  • Private fields in JavaScript. A field whose name starts with #, such as #width, can be used only inside the class body. "In JavaScript, private elements use a special identifier syntax, so modifier keywords like public and private should not be used either."2

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • zero-side: a side of 0 gives an area of 0 and a perimeter of twice the other side.
  • zero-factor: a factor of 0 makes both sides 0, so the area and the perimeter after the scale are 0.
  • identity: a factor of 1 leaves the rectangle as it was.
  • limit: 1000 by 1000 scaled by 46 has the area 2,116,000,000, which is less than 2^31 - 1, the largest signed 32-bit integer. A factor of 47 gives 2,209,000,000, which does not fit, so the contract does not allow it.

Pitfalls

  • A Python class attribute is shared by all instances. An attribute assigned in the class body belongs to the class, not to each instance. If it is a list, every instance appends to the same list. The tutorial warns that "shared data can have possibly surprising effects involving mutable objects such as lists and dictionaries".1 Make the list in __init__:
class Basket:
    items = []  # a class attribute: one list for all instances

    def add(self, item):
        self.items.append(item)


class FixedBasket:
    def __init__(self):
        self.items = []  # an instance attribute: one list per instance

    def add(self, item):
        self.items.append(item)


a, b = Basket(), Basket()
a.add("apple")
print(b.items)

c, d = FixedBasket(), FixedBasket()
c.add("apple")
print(d.items)
Output
['apple']
[]
  • A Go method with a value receiver changes a copy. Scale below has the receiver r Rectangle, so it gets a copy of the rectangle, and the change is lost. Grow has the receiver r *Rectangle and changes the caller's rectangle:
package main

import "fmt"

type Rectangle struct{ width, height int }

// A value receiver: Scale changes a copy.
func (r Rectangle) Scale(factor int) {
	r.width *= factor
	r.height *= factor
}

// A pointer receiver: Grow changes the caller's rectangle.
func (r *Rectangle) Grow(factor int) {
	r.width *= factor
	r.height *= factor
}

func main() {
	r := Rectangle{3, 4}
	r.Scale(2)
	fmt.Println(r)
	r.Grow(2)
	fmt.Println(r)
}
Output
{3 4}
{6 8}
  • A Java or C# parameter with the name of a field hides the field. In a constructor Rectangle(int width, int height), the statement width = width; assigns the parameter to itself, and the field keeps its default value 0. Write this.width = width;. Python has the same trap without self.: width = width in __init__ makes a local variable.
  • A JavaScript class cannot be used before its declaration. Function declarations can be called before they appear in the code, but class declarations "behave as if they are not hoisted".2 Code that runs new Rectangle(1, 2) above class Rectangle throws a ReferenceError.

Code

The build runs the native tests of each language in a pinned toolchain.

rectangle.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-class/.


class Rectangle:
    """A rectangle with a width and a height."""

    def __init__(self, width: int, height: int) -> None:
        # The constructor sets the fields of the new instance on self.
        self.width = width
        self.height = height

    def area(self) -> int:
        return self.width * self.height

    def perimeter(self) -> int:
        return 2 * (self.width + self.height)

    def scale(self, factor: int) -> None:
        """Multiply both sides by factor. This changes the instance."""
        self.width *= factor
        self.height *= factor

    def __repr__(self) -> str:
        return f"Rectangle({self.width}, {self.height})"


def rectangle_report(width: int, height: int, factor: int) -> list[int]:
    r = Rectangle(width, height)
    before = [r.area(), r.perimeter()]
    r.scale(factor)
    return before + [r.area(), r.perimeter()]
test_rectangle.py 30 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/define-a-class/.

import pytest

from rectangle import Rectangle, rectangle_report

CASES = {
    "three-by-four": ((3, 4, 2), [12, 14, 48, 28]),
    "square": ((5, 5, 3), [25, 20, 225, 60]),
    "zero-side": ((0, 7, 2), [0, 14, 0, 28]),
    "zero-factor": ((3, 4, 0), [12, 14, 0, 0]),
    "identity": ((3, 4, 1), [12, 14, 12, 14]),
    "limit": ((1000, 1000, 46), [1000000, 4000, 2116000000, 184000]),
}


@pytest.mark.parametrize("name", CASES)
def test_rectangle_report(name):
    args, want = CASES[name]
    assert rectangle_report(*args) == want


def test_instances_have_their_own_fields():
    a = Rectangle(1, 2)
    b = Rectangle(1, 2)
    a.scale(3)
    assert (a.width, a.height) == (3, 6)
    assert (b.width, b.height) == (1, 2)
    assert repr(a) == "Rectangle(3, 6)"
rectangle.cppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

#include "rectangle.hpp"

void Rectangle::scale(int factor) {
    width_ *= factor;
    height_ *= factor;
}

std::string Rectangle::to_string() const {
    return "Rectangle(" + std::to_string(width_) + ", " + std::to_string(height_) + ")";
}

std::vector<int> rectangle_report(int width, int height, int factor) {
    Rectangle r(width, height);
    std::vector<int> out{r.area(), r.perimeter()};
    r.scale(factor);
    out.push_back(r.area());
    out.push_back(r.perimeter());
    return out;
}
rectangle.hpp 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

#pragma once

#include <string>
#include <vector>

// A rectangle with a width and a height.
class Rectangle {
public:
    Rectangle(int width, int height) : width_(width), height_(height) {}

    // const after the parameter list: the method does not change the object.
    int area() const { return width_ * height_; }
    int perimeter() const { return 2 * (width_ + height_); }

    // Multiplies both sides by factor. This changes the object.
    void scale(int factor);

    std::string to_string() const;

private:
    int width_;
    int height_;
};

// rectangle_report returns the area and the perimeter, before and after
// scale(factor).
std::vector<int> rectangle_report(int width, int height, int factor);
test_rectangle.cpp 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

#include "rectangle.hpp"

#include <iostream>
#include <string_view>
#include <vector>

static int failures = 0;

static void check(std::string_view name, int width, int height, int factor, const std::vector<int> &want) {
    if (rectangle_report(width, height, factor) != want) {
        std::cerr << "case " << name << " failed\n";
        failures++;
    }
}

int main() {
    check("three-by-four", 3, 4, 2, {12, 14, 48, 28});
    check("square", 5, 5, 3, {25, 20, 225, 60});
    check("zero-side", 0, 7, 2, {0, 14, 0, 28});
    check("zero-factor", 3, 4, 0, {12, 14, 0, 0});
    check("identity", 3, 4, 1, {12, 14, 12, 14});
    check("limit", 1000, 1000, 46, {1000000, 4000, 2116000000, 184000});

    Rectangle a(1, 2);
    Rectangle b(1, 2);
    a.scale(3);
    if (a.to_string() != "Rectangle(3, 6)" || b.to_string() != "Rectangle(1, 2)") {
        std::cerr << "case own-fields failed\n";
        failures++;
    }
    if (failures > 0) {
        return 1;
    }
    std::cout << "all cases pass\n";
    return 0;
}
Rectangle.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

import java.util.List;

/** A rectangle with a width and a height. */
final class Rectangle {
  // Private fields: only the code of this class can read or change them.
  private int width;
  private int height;

  Rectangle(int width, int height) {
    this.width = width;
    this.height = height;
  }

  int width() {
    return width;
  }

  int height() {
    return height;
  }

  int area() {
    return width * height;
  }

  int perimeter() {
    return 2 * (width + height);
  }

  /** Multiplies both sides by factor. This changes the instance. */
  void scale(int factor) {
    width *= factor;
    height *= factor;
  }

  @Override
  public String toString() {
    return "Rectangle(" + width + ", " + height + ")";
  }

  static List<Integer> rectangleReport(int width, int height, int factor) {
    Rectangle r = new Rectangle(width, height);
    int area = r.area();
    int perimeter = r.perimeter();
    r.scale(factor);
    return List.of(area, perimeter, r.area(), r.perimeter());
  }
}
RectangleTest.java 38 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.util.List;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class RectangleTest {
  static Stream<Arguments> cases() {
    return Stream.of(
        Arguments.of("three-by-four", 3, 4, 2, List.of(12, 14, 48, 28)),
        Arguments.of("square", 5, 5, 3, List.of(25, 20, 225, 60)),
        Arguments.of("zero-side", 0, 7, 2, List.of(0, 14, 0, 28)),
        Arguments.of("zero-factor", 3, 4, 0, List.of(12, 14, 0, 0)),
        Arguments.of("identity", 3, 4, 1, List.of(12, 14, 12, 14)),
        Arguments.of("limit", 1000, 1000, 46, List.of(1000000, 4000, 2116000000, 184000)));
  }

  @ParameterizedTest(name = "{0}")
  @MethodSource("cases")
  void rectangleReport(String name, int width, int height, int factor, List<Integer> want) {
    assertEquals(want, Rectangle.rectangleReport(width, height, factor));
  }

  @Test
  void instancesHaveTheirOwnFields() {
    Rectangle a = new Rectangle(1, 2);
    Rectangle b = new Rectangle(1, 2);
    a.scale(3);
    assertEquals("Rectangle(3, 6)", a.toString());
    assertEquals("Rectangle(1, 2)", b.toString());
  }
}
rectangle.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

#include "rectangle.h"

struct rectangle rectangle_make(int width, int height) {
    return (struct rectangle){.width = width, .height = height};
}

// A const pointer: the function reads the rectangle and cannot change it.
int rectangle_area(const struct rectangle *r) {
    return r->width * r->height;
}

int rectangle_perimeter(const struct rectangle *r) {
    return 2 * (r->width + r->height);
}

void rectangle_scale(struct rectangle *r, int factor) {
    r->width *= factor;
    r->height *= factor;
}

void rectangle_report(int width, int height, int factor, int out[4]) {
    struct rectangle r = rectangle_make(width, height);
    out[0] = rectangle_area(&r);
    out[1] = rectangle_perimeter(&r);
    rectangle_scale(&r, factor);
    out[2] = rectangle_area(&r);
    out[3] = rectangle_perimeter(&r);
}
rectangle.h 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

#ifndef RECTANGLE_H
#define RECTANGLE_H

// C has no classes. A struct holds the fields, and functions that take a
// pointer to the struct play the part of methods.
struct rectangle {
    int width;
    int height;
};

struct rectangle rectangle_make(int width, int height);
int rectangle_area(const struct rectangle *r);
int rectangle_perimeter(const struct rectangle *r);
void rectangle_scale(struct rectangle *r, int factor);

// rectangle_report writes the area and the perimeter, before and after
// rectangle_scale(factor), to out[0] to out[3].
void rectangle_report(int width, int height, int factor, int out[4]);

#endif
test_rectangle.c 42 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

#include "rectangle.h"

#include <stdio.h>
#include <string.h>

static int failures = 0;

static void check(const char *name, int width, int height, int factor, int a, int b, int c, int d) {
    const int want[4] = {a, b, c, d};
    int got[4];
    rectangle_report(width, height, factor, got);
    if (memcmp(got, want, sizeof want) != 0) {
        fprintf(stderr, "case %s failed\n", name);
        failures++;
    }
}

int main(void) {
    check("three-by-four", 3, 4, 2, 12, 14, 48, 28);
    check("square", 5, 5, 3, 25, 20, 225, 60);
    check("zero-side", 0, 7, 2, 0, 14, 0, 28);
    check("zero-factor", 3, 4, 0, 12, 14, 0, 0);
    check("identity", 3, 4, 1, 12, 14, 12, 14);
    check("limit", 1000, 1000, 46, 1000000, 4000, 2116000000, 184000);

    // Each struct value has its own fields.
    struct rectangle a = rectangle_make(1, 2);
    struct rectangle b = rectangle_make(1, 2);
    rectangle_scale(&a, 3);
    if (a.width != 3 || a.height != 6 || b.width != 1 || b.height != 2) {
        fprintf(stderr, "case own-fields failed\n");
        failures++;
    }
    if (failures > 0) {
        return 1;
    }
    printf("all cases pass\n");
    return 0;
}
Rectangle.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

/// <summary>A rectangle with a width and a height.</summary>
public sealed class Rectangle
{
    // Properties with a private setter: other code can read them, and only
    // the methods of this class can change them.
    public int Width { get; private set; }
    public int Height { get; private set; }

    public Rectangle(int width, int height)
    {
        Width = width;
        Height = height;
    }

    public int Area() => Width * Height;

    public int Perimeter() => 2 * (Width + Height);

    /// <summary>Multiplies both sides by factor. This changes the instance.</summary>
    public void Scale(int factor)
    {
        Width *= factor;
        Height *= factor;
    }

    public override string ToString() => $"Rectangle({Width}, {Height})";

    public static int[] Report(int width, int height, int factor)
    {
        var r = new Rectangle(width, height);
        int area = r.Area();
        int perimeter = r.Perimeter();
        r.Scale(factor);
        return [area, perimeter, r.Area(), r.Perimeter()];
    }
}
RectangleTests.cs 35 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

using Xunit;

public sealed class RectangleTests
{
    public static TheoryData<string, int, int, int, int[]> Cases => new()
    {
        { "three-by-four", 3, 4, 2, new[] { 12, 14, 48, 28 } },
        { "square", 5, 5, 3, new[] { 25, 20, 225, 60 } },
        { "zero-side", 0, 7, 2, new[] { 0, 14, 0, 28 } },
        { "zero-factor", 3, 4, 0, new[] { 12, 14, 0, 0 } },
        { "identity", 3, 4, 1, new[] { 12, 14, 12, 14 } },
        { "limit", 1000, 1000, 46, new[] { 1000000, 4000, 2116000000, 184000 } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void Report(string name, int width, int height, int factor, int[] want)
    {
        Assert.NotNull(name);
        Assert.Equal(want, Rectangle.Report(width, height, factor));
    }

    [Fact]
    public void InstancesHaveTheirOwnFields()
    {
        var a = new Rectangle(1, 2);
        var b = new Rectangle(1, 2);
        a.Scale(3);
        Assert.Equal("Rectangle(3, 6)", a.ToString());
        Assert.Equal("Rectangle(1, 2)", b.ToString());
    }
}
rectangle.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

export class Rectangle {
  // Fields declared in the class body. Each instance gets its own copy.
  width;
  height;

  constructor(width, height) {
    this.width = width;
    this.height = height;
  }

  area() {
    return this.width * this.height;
  }

  perimeter() {
    return 2 * (this.width + this.height);
  }

  /** Multiplies both sides by factor. This changes the instance. */
  scale(factor) {
    this.width *= factor;
    this.height *= factor;
  }
}

/**
 * @param {number} width
 * @param {number} height
 * @param {number} factor
 * @returns {number[]}
 */
export function rectangleReport(width, height, factor) {
  const r = new Rectangle(width, height);
  const before = [r.area(), r.perimeter()];
  r.scale(factor);
  return [...before, r.area(), r.perimeter()];
}
rectangle.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { Rectangle, rectangleReport } from "./rectangle.js";

const cases = [
  ["three-by-four", [3, 4, 2], [12, 14, 48, 28]],
  ["square", [5, 5, 3], [25, 20, 225, 60]],
  ["zero-side", [0, 7, 2], [0, 14, 0, 28]],
  ["zero-factor", [3, 4, 0], [12, 14, 0, 0]],
  ["identity", [3, 4, 1], [12, 14, 12, 14]],
  ["limit", [1000, 1000, 46], [1000000, 4000, 2116000000, 184000]],
];

for (const [name, args, want] of cases) {
  test(name, () => {
    assert.deepEqual(rectangleReport(...args), want);
  });
}

test("instances have their own fields", () => {
  const a = new Rectangle(1, 2);
  const b = new Rectangle(1, 2);
  a.scale(3);
  assert.deepEqual([a.width, a.height], [3, 6]);
  assert.deepEqual([b.width, b.height], [1, 2]);
  assert.equal(a instanceof Rectangle, true);
});
rectangle.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

export class Rectangle {
  // The fields have types, and the compiler checks that the constructor sets them.
  width: number;
  height: number;

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

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

  perimeter(): number {
    return 2 * (this.width + this.height);
  }

  /** Multiplies both sides by factor. This changes the instance. */
  scale(factor: number): void {
    this.width *= factor;
    this.height *= factor;
  }
}

export function rectangleReport(width: number, height: number, factor: number): number[] {
  const r = new Rectangle(width, height);
  const before = [r.area(), r.perimeter()];
  r.scale(factor);
  return [...before, r.area(), r.perimeter()];
}
rectangle.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { Rectangle, rectangleReport } from "./rectangle.ts";

const cases: [string, [number, number, number], number[]][] = [
  ["three-by-four", [3, 4, 2], [12, 14, 48, 28]],
  ["square", [5, 5, 3], [25, 20, 225, 60]],
  ["zero-side", [0, 7, 2], [0, 14, 0, 28]],
  ["zero-factor", [3, 4, 0], [12, 14, 0, 0]],
  ["identity", [3, 4, 1], [12, 14, 12, 14]],
  ["limit", [1000, 1000, 46], [1000000, 4000, 2116000000, 184000]],
];

for (const [name, args, want] of cases) {
  test(name, () => {
    assert.deepEqual(rectangleReport(...args), want);
  });
}

test("instances have their own fields", () => {
  const a = new Rectangle(1, 2);
  const b = new Rectangle(1, 2);
  a.scale(3);
  assert.deepEqual([a.width, a.height], [3, 6]);
  assert.deepEqual([b.width, b.height], [1, 2]);
  assert.equal(a instanceof Rectangle, true);
});
rectangle.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

// Package rectangle defines a struct type with methods, which is how Go
// writes a class.
package rectangle

import "fmt"

// Rectangle has a width and a height. The fields start with a lower-case
// letter, so code outside the package cannot see them.
type Rectangle struct {
	width, height int
}

// New plays the part of a constructor. Go has no constructors, so a function
// makes the value.
func New(width, height int) *Rectangle {
	return &Rectangle{width: width, height: height}
}

// Area has a value receiver: it reads a copy of the rectangle.
func (r Rectangle) Area() int { return r.width * r.height }

// Perimeter has a value receiver too.
func (r Rectangle) Perimeter() int { return 2 * (r.width + r.height) }

// Scale multiplies both sides by factor. It changes the rectangle, so it has
// a pointer receiver.
func (r *Rectangle) Scale(factor int) {
	r.width *= factor
	r.height *= factor
}

// String makes fmt print a Rectangle as Rectangle(w, h).
func (r Rectangle) String() string {
	return fmt.Sprintf("Rectangle(%d, %d)", r.width, r.height)
}

// Report returns the area and the perimeter, before and after Scale(factor).
func Report(width, height, factor int) []int {
	r := New(width, height)
	out := []int{r.Area(), r.Perimeter()}
	r.Scale(factor)
	return append(out, r.Area(), r.Perimeter())
}
rectangle_test.go 39 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

package rectangle

import (
	"slices"
	"testing"
)

var cases = []struct {
	name                   string
	width, height, factor  int
	want                   []int
}{
	{"three-by-four", 3, 4, 2, []int{12, 14, 48, 28}},
	{"square", 5, 5, 3, []int{25, 20, 225, 60}},
	{"zero-side", 0, 7, 2, []int{0, 14, 0, 28}},
	{"zero-factor", 3, 4, 0, []int{12, 14, 0, 0}},
	{"identity", 3, 4, 1, []int{12, 14, 12, 14}},
	{"limit", 1000, 1000, 46, []int{1000000, 4000, 2116000000, 184000}},
}

func TestReport(t *testing.T) {
	for _, c := range cases {
		if got := Report(c.width, c.height, c.factor); !slices.Equal(got, c.want) {
			t.Errorf("%s: got %v, want %v", c.name, got, c.want)
		}
	}
}

func TestInstancesHaveTheirOwnFields(t *testing.T) {
	a := New(1, 2)
	b := New(1, 2)
	a.Scale(3)
	if a.String() != "Rectangle(3, 6)" || b.String() != "Rectangle(1, 2)" {
		t.Errorf("got %v and %v", a, b)
	}
}
rectangle.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

use std::fmt;

/// A rectangle with a width and a height. Rust has no classes: a struct holds
/// the fields, and an impl block holds the methods.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    /// An associated function with the conventional name new. Rust has no
    /// constructors.
    pub fn new(width: u32, height: u32) -> Self {
        Self { width, height }
    }

    /// &self borrows the rectangle to read it.
    pub fn area(&self) -> u32 {
        self.width * self.height
    }

    pub fn perimeter(&self) -> u32 {
        2 * (self.width + self.height)
    }

    /// &mut self borrows the rectangle to change it.
    pub fn scale(&mut self, factor: u32) {
        self.width *= factor;
        self.height *= factor;
    }
}

impl fmt::Display for Rectangle {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Rectangle({}, {})", self.width, self.height)
    }
}

/// Returns the area and the perimeter, before and after scale(factor).
pub fn rectangle_report(width: u32, height: u32, factor: u32) -> Vec<u32> {
    let mut r = Rectangle::new(width, height);
    let mut out = vec![r.area(), r.perimeter()];
    r.scale(factor);
    out.extend([r.area(), r.perimeter()]);
    out
}
tests/rectangle_test.rs 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/define-a-class/.

use algo_define_a_class::{rectangle_report, Rectangle};

#[test]
fn cases() {
    let cases: Vec<(&str, (u32, u32, u32), Vec<u32>)> = vec![
        ("three-by-four", (3, 4, 2), vec![12, 14, 48, 28]),
        ("square", (5, 5, 3), vec![25, 20, 225, 60]),
        ("zero-side", (0, 7, 2), vec![0, 14, 0, 28]),
        ("zero-factor", (3, 4, 0), vec![12, 14, 0, 0]),
        ("identity", (3, 4, 1), vec![12, 14, 12, 14]),
        ("limit", (1000, 1000, 46), vec![1000000, 4000, 2116000000, 184000]),
    ];
    for (name, (w, h, k), want) in cases {
        assert_eq!(rectangle_report(w, h, k), want, "{name}");
    }
}

#[test]
fn instances_have_their_own_fields() {
    let mut a = Rectangle::new(1, 2);
    let b = Rectangle::new(1, 2);
    a.scale(3);
    assert_eq!(a.to_string(), "Rectangle(3, 6)");
    assert_eq!(b.to_string(), "Rectangle(1, 2)");
}

References

  1. 9. Classes, The Python Tutorial, 9.3.2 Class Objects; 9.3.5 Class and Instance Variables
  2. Classes, MDN Web Docs, Defining classes; Class body
  3. Classes, TypeScript Handbook, Fields; --strictPropertyInitialization
  4. Chapter 8, Classes, The Java Language Specification, Java SE 25 Edition, 8.8.9 Default Constructor
  5. Introduction to classes, C# fundamentals, Reference types; Constructors and initialization
  6. Classes, cppreference.com, Introduction
  7. The Go Programming Language Specification, Method declarations
  8. Methods, The Rust Programming Language, Method Syntax; Associated Functions

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source