Use Cases
This example is intended to demonstrate the extensibility differences between data structures and objects by extending them with
- an Area() function (extending behavior)
- a rectangle type (extending data type)
Data Structure Style
interface GeometricObject {}
class Square implements GeometricObject {
length float
}
class Circle implements GeometricObject {
radius float
}
function Circumference(g GeometricObject) float {
switch type(g):
case Square:
return 4 * g.length
case Circle:
return 2 * PI * g.radius
}
class Square implements GeometricObject {
length float
}
class Circle implements GeometricObject {
radius float
}
function Circumference(g GeometricObject) float {
switch type(g):
case Square:
return 4 * g.length
case Circle:
return 2 * PI * g.radius
}
- Adding an Area() function with a very similar anatomy to Circumference() is easy because it only requires adding new code.
- Adding a new datatype, Rectangle, is harder 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
}
}
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
}
}
- Adding a function Area() to the GeometricObject interface is hard because it requires touching existing code, namely extending all Square and Circle classes with the new function.
- Adding a new datatype, Rectangle, is easy because only new code is added, namely a Rectangle class.
Conclusion
- The lesson here is that data structures are easy to extend with functions and hard to extend with data type, and objects are easy to extend with other objects but hard to extend with functionality.
- Although the difference between the two styles may seem insignificant in this simplified example, it has serious implications in complex production codebases with multiple data types and behaviors.