Wiki source code of Code Example: Data Structure Style vs. Object Style
Hide last authors
| author | version | line-number | content |
|---|---|---|---|
| |
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 | |||
| |
2.4 | 8 | ### Data Structure Style |
| |
2.1 | 9 | |
| |
3.5 | 10 | struct Square { |
| |
2.4 | 11 | length float |
| 12 | } | ||
| 13 | |||
| |
3.5 | 14 | struct Circle { |
| |
3.2 | 15 | radius float |
| |
2.4 | 16 | } |
| 17 | |||
| |
3.5 | 18 | function Circumference(g Object) float { |
| |
3.2 | 19 | switch type(g): |
| 20 | case Square: | ||
| 21 | return 4 * g.length | ||
| 22 | case Circle: | ||
| 23 | return 2 * PI * g.radius | ||
| |
2.4 | 24 | } |
| |
2.1 | 25 | |
| |
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. | ||
| |
3.3 | 28 | |
| |
3.4 | 29 | #### |
| 30 | |||
| |
2.3 | 31 | #### Object-Oriented Style |
| |
2.2 | 32 | |
| |
3.3 | 33 | interface GeometricObject { |
| 34 | Circumference() float | ||
| 35 | } | ||
| 36 | |||
| 37 | class Square implements GeometricObject { | ||
| |
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 | |||
| |
3.3 | 49 | class Circle implements GeometricObject { |
| |
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 | } |