Code Example: Data Structure Style vs. Object Style

Version 3.3 by chrisby on 2024/03/03 14:57

Data Structure Style

type Square struct {
  length float
}

type Circle struct {
  radius float
}

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

Object-Oriented Style

interface GeometricObject {
  Circumference() float
}

class Square implements GeometricObject {
  length float

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

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

class Circle implements GeometricObject {
  radius float

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

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