Code Example: Data Structure Style vs. Object Style

Version 3.2 by chrisby on 2024/03/03 14:50

Data Structure Style

type Square struct {
  length float
}

type Circle struct {
  radius float
}

func Area(g GeometricObject) float {
  switch type(g):
    case Square:
      return g.length * g.length
    case Circle:
      return PI * g.radius * g.radius
}

func Circumference(g GeometricObject) float {
  switch type(g):
    case Square:
      return 4 * g.length
    case Circle:
      return 2 * PI * g.radius
}

Object-Oriented Style

class Square {
  length float

  constructor(length float) {
    this.length = length
  }

  func Area() float {
    return this.length * this.length
  }

  func Circumference() float {
    return 4 * this.length
  }
}

class Circle {
  radius float

  constructor(radius float) {
    this.radius = radius
  }

  func Area() float {
    return PI * this.radius * this.radius
  }

  func Circumference() float {
    return 2 * PI * this.radius
  }
}