Code Example: Data Structure Style vs. Object Style

Version 3.5 by chrisby on 2024/03/03 15:17

Use Cases

This example is intended to demonstrate the extensibility differences between data structures and objects by extending them with

  1. an Area() function (extending behavior)
  2. a rectangle type (extending data type)

Data Structure Style

struct Square {
  length float
}

struct Circle {
  radius float
}

function Circumference(g Object) float {
  switch type(g):
    case Square:
      return 4 * g.length
    case Circle:
      return 2 * PI * g.radius
}
  1. Adding a function Area() with the same anatomy as Circumference() is easy, since it only requires adding new code.
  2. Adding a new datatype, Rectangle, is more difficult because it requires touching existing code, namely any functions like Circumference() or Area() that need to be enabled handle this datatype.

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
  }
}