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

Hide last authors
chrisby 3.4 1 ### Use Cases
2
3 This example is intended to demonstrate the extensibility differences between data structures and objects by extending them with
4
5 1. an Area() function (extending behavior)
6 1. a rectangle type (extending data type)
7
chrisby 2.4 8 ### Data Structure Style
chrisby 2.1 9
chrisby 3.5 10 struct Square {
chrisby 2.4 11 length float
12 }
13
chrisby 3.5 14 struct Circle {
chrisby 3.2 15 radius float
chrisby 2.4 16 }
17
chrisby 3.5 18 function Circumference(g Object) float {
chrisby 3.2 19 switch type(g):
20 case Square:
21 return 4 * g.length
22 case Circle:
23 return 2 * PI * g.radius
chrisby 2.4 24 }
chrisby 2.1 25
chrisby 3.5 26 1. Adding a function Area() with the same anatomy as Circumference() is easy, since it only requires adding new code.
27 1. 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.
chrisby 3.3 28
chrisby 3.4 29 ####
30
chrisby 2.3 31 #### Object-Oriented Style
chrisby 2.2 32
chrisby 3.3 33 interface GeometricObject {
34 Circumference() float
35 }
36
37 class Square implements GeometricObject {
chrisby 2.3 38 length float
39
40 constructor(length float) {
41 this.length = length
42 }
43
44 func Circumference() float {
45 return 4 * this.length
46 }
47 }
48
chrisby 3.3 49 class Circle implements GeometricObject {
chrisby 2.3 50 radius float
51
52 constructor(radius float) {
53 this.radius = radius
54 }
55
56 func Circumference() float {
57 return 2 * PI * this.radius
58 }
59 }