-
Notifications
You must be signed in to change notification settings - Fork 32
/
oop.tex
494 lines (411 loc) · 14.4 KB
/
oop.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
\chapter{Objects and Classes}\label{s:oop}
Making new code use old code is easy:
just load the libraries you want and write calls to the functions you need.
Making \emph{old} code use \emph{new} code without rewriting it is trickier,
but \grefdex{g:oop}{object-oriented programming}{programming!object-oriented} (OOP) can help.
\section{Doing It By Hand}\label{s:oop-manual}
As we saw in \chapref{s:basics},
an object in JavaScript is a set of key-value pairs.
Since functions are just another kind of data,
an object's values can be functions,
so data can carry around functions that work on it.
For example,
we can create an object to represent a square:
\begin{minted}{js}
const square = {
name: 'square',
size: 5,
area: (it) => { return it.size * it.size },
perimeter: (it) => { return 4 * it.size }
}
\end{minted}
\noindent
and then pass the object itself into each of its own functions:
\begin{minted}{js}
const a = square.area(square)
console.log(`area of square is ${a}`)
\end{minted}
\begin{minted}{text}
area of square is 25
\end{minted}
This is clumsy---we'll often forget to pass the object into its functions---but
it allows us to handle many different kinds of things in the same way.
For example,
we can create another object to represent a circle:
\begin{minted}{js}
const circle = {
name: 'circle',
radius: 3,
area: (it) => { return Math.PI * it.radius * it.radius },
perimeter: (it) => { return 2 * Math.PI * it.radius }
}
\end{minted}
\noindent
and then put all of these different objects in an array
and operate on them in the same way
without knowing precisely what kind of object we're dealing with:
\begin{minted}{js}
const show_all = (shapes) => {
for (let s of shapes) {
const a = s.area(s)
const p = s.perimeter(s)
console.log(`${s.name}: area ${a} perimeter ${p}`)
}
}
show_all([square, circle])
\end{minted}
\begin{minted}{text}
square: area 25 perimeter 20
circle: area 28.274333882308138 perimeter 18.84955592153876
\end{minted}
As long as we only use the value \texttt{name} and the functions \texttt{area} and \texttt{perimeter}
we don't need to know what kind of shape we have.
This is called \gref{g:polymorphism}{polymorphism},
and it allows us to add new shapes without changing the code in our loop.
In other words,
it allows old code (in this case, the function \texttt{show\_all})
to use new code (the new object \texttt{rectangle}):
\begin{minted}{js}
const rectangle = {
name: 'rectangle',
width: 2,
height: 3,
area: (it) => { return it.width * it.height },
perimeter: (it) => { return 2 * (it.width + it.height) }
}
show_all([square, circle, rectangle])
\end{minted}
\begin{minted}{text}
square: area 25 perimeter 20
circle: area 28.274333882308138 perimeter 18.84955592153876
rectangle: area 6 perimeter 10
\end{minted}
\section{Classes}\label{s:oop-classes}
Building every object by hand and calling \texttt{thing.function(thing)} is clumsy.
JavaScript solved these problems using \grefdex{g:prototype}{prototypes}{prototype},
which turned out to be almost as clumsy as our hand-rolled solution (\secref{s:legacy-prototypes}).
Most object-oriented languages use \grefdex{g:class}{classes}{class!in JavaScript} instead (\figref{f:oop-memory});
these were added to JavaScript in ES6,
and we will use them instead of prototypes throughout.
Here's how we create a class that defines the properties of a square,
without actually creating any specific squares:
\begin{minted}{js}
class Square {
constructor (size) {
this.name = 'square'
this.size = size
}
area () { return this.size * this.size }
perimeter () { return 4 * this.size }
}
\end{minted}
\noindent
(Class names are written in CamelCase\index{camel case} by convention.)
We can then create a specific square by using the class's name as if it were a function:
\begin{minted}{js}
const sq = new Square(3)
console.log(`sq name ${sq.name} and area ${sq.area()}`)
\end{minted}
\begin{minted}{text}
sq name square and area 9
\end{minted}
\texttt{new\ ClassName(...)} creates a new blank object
and marks it to show that it is an \gref{g:instance}{instance} of \texttt{ClassName}.
Objects need to know what class they belong to
so that they can find their \grefdex{g:method}{methods}{method},
which are the functions defined within the class
that operate on instances of it.
(We'll explain how JavaScript marks objects in \secref{s:legacy-prototypes};
it's more complicated than it needs to be
in order to be compatible with older versions of the language.)
\figpdf{figures/oop-memory.pdf}{Objects and Classes in Memory}{f:oop-memory}
Before \texttt{new} hands the newly-created object back to the program,
it calls the specially-named \gref{g:constructor}{constructor}
to initialize the object's state.
Inside the constructor and other methods,
the object being operated on is referred to by the pronoun \texttt{this}.\index{this|texttt}
For example,
if the constructor assigns an array to \texttt{this.values},
then every instance of that class gets its own array.
\begin{aside}{Everything Old is New Again}
Methods are defined within a class using classic \texttt{function} syntax
rather than the fat arrows we have been using.
The inconsistency is unfortunate
but this way of defining methods is what the current version of Node prefers;
we will explore this topic further in \chapref{s:vis}.
\end{aside}
There are a lot of new terms packed into the preceding three paragraphs,
so let's retrace the execution of:
\begin{minted}{js}
const sq = new Square(3)
console.log(`sq name ${sq.name} and area ${sq.area()}`)
\end{minted}
\begin{enumerate}
\item
\texttt{new} creates a blank object,
then looks up the definition of the class \texttt{Square}
and calls the \texttt{constructor} defined inside it
with the value 3.
\item
Inside that call,
\texttt{this} refers to the newly-created blank object.
The constructor adds two keys to the object:
\texttt{name}, which has the value \texttt{'square'},
and \texttt{size}, which has the value 3.
\item
Once the constructor finishes,
the newly-created object is assigned to the variable \texttt{sq}.
\item
In order to create a string to pass to \texttt{console.log},
the program has to look up the value of \texttt{sq.name},
which works like looking up any other key in an object.
\item
The program also has to call \texttt{sq.area}.
During that call,
JavaScript temporarily assigns \texttt{sq} to the variable \texttt{this}
so that the \texttt{area} method can look up the value of \texttt{size}
in the object it's being called for.
\item
Finally,
the program fills in the template string and calls \texttt{console.log}.
\end{enumerate}
JavaScript classes support polymorphism:\index{polymorphism}
if two or more classes have some methods with the same names
that take the same parameters
and return the same kinds of values,
other code can use objects of those classes interchangeably.
For example,
here's a class-based rewrite of our shapes code:
\begin{minted}{js}
class Circle {
constructor (radius) {
this.name = 'circle'
this.radius = radius
}
area () { return Math.PI * this.radius * this.radius }
perimeter () { return 2 * Math.PI * this.radius }
}
class Rectangle {
constructor (width, height) {
this.name = 'rectangle'
this.width = width
this.height = height
}
area () { return this.width * this.height }
perimeter () { return 2 * (this.width + this.height) }
}
const everything = [
new Square(3.5),
new Circle(2.5),
new Rectangle(1.5, 0.5)
]
for (let thing of everything) {
const a = thing.area(thing)
const p = thing.perimeter(thing)
console.log(`${thing.name}: area ${a} perimeter ${p}`)
}
\end{minted}
\begin{minted}{text}
square: area 12.25 perimeter 14
circle: area 19.634954084936208 perimeter 15.707963267948966
rectangle: area 0.75 perimeter 4
\end{minted}
\section{Inheritance}\label{s:oop-inheritance}
We can build new classes from old ones
by adding or \grefdex{g:override-method}{overriding}{method!override} methods.\index{overriding methods}
To show this,
we'll start by defining a person:
\begin{minted}{js}
class Person {
constructor (name) {
this.name = name
}
greeting (formal) {
if (formal) {
return `Hello, my name is ${this.name}`
} else {
return `Hi, I'm ${this.name}`
}
}
farewell () {
return `Goodbye`
}
}
\end{minted}
This class allows us to create an instance with a formal greeting:
\begin{minted}{js}
const parent = new Person('Hakim')
console.log(`parent: ${parent.greeting(true)} - ${parent.farewell()}`)
\end{minted}
\begin{minted}{text}
parent: Hello, my name is Hakim - Goodbye
\end{minted}
We can now \grefdex{g:extend}{extend}{extension}\index{class!extension} \texttt{Person}
to create a new class \texttt{Scientist},
in which case we say that \texttt{Scientist} \grefdex{g:inherit}{inherits}{inheritance}\index{class!inheritance} from \texttt{Person},
or that \texttt{Person} is a \gref{g:parent-class}{parent class}\index{class!parent} of \texttt{Scientist}
and \texttt{Scientist} is a \gref{g:child-class}{child class}\index{class!child} of \texttt{Person}.
\begin{minted}{js}
class Scientist extends Person {
constructor (name, area) {
super(name)
this.area = area
}
greeting (formal) {
return `${super.greeting(formal)}. Let's talk about ${this.area}...`
}
}
\end{minted}
This tells us that a \texttt{Scientist} is a \texttt{Person} who:
\begin{itemize}
\item
Has an area of specialization as well as a name.
\item
Says hello in a slightly longer way
\item
Says goodbye in the same way as a \texttt{Person}
(since \texttt{Scientist} \emph{doesn't} define its own \texttt{farewell} method)
\end{itemize}
The word \texttt{super}\index{super|texttt} is used in two ways here:
\begin{itemize}
\item
In the constructor for \texttt{Scientist},
\texttt{super(...)} calls up to the constructor of the parent class \texttt{Person}
so that it can do whatever initialization it does
before \texttt{Scientist} does its own initialization.
This saves us from duplicating steps.
\item
Inside \texttt{greeting},
the expression \texttt{super.greeting(formal)} means
``call the parent class's \texttt{greeting} method for this object''.
This allows methods defined in child classes to add to or modify
the behavior of methods defined in parent classes,
again without duplicating code.
\end{itemize}
Let's try it out:
\begin{minted}{js}
const child = new Scientist('Bhadra', 'microbiology')
console.log(`child: ${child.greeting(false)} - ${child.farewell()}`)
\end{minted}
\begin{minted}{text}
child: Hi, I'm Bhadra. Let's talk about microbiology... - Goodbye
\end{minted}
\figref{f:oop-inheritance} shows what memory looks like after these classes have been defined
and the objects \texttt{parent} and \texttt{child} have been created.
It looks complex at first,
but allows us to see how JavaScript finds the right method
when \texttt{child.farewell()} is called:
\begin{itemize}
\item
It looks in the object \texttt{child} to see if there's a function there with the right name.
\item
There isn't, so it follows \texttt{child}'s link to its class \texttt{Scientist}
to see if a function is there.
\item
There isn't, so it follows the link from \texttt{Scientist} to the parent class \texttt{Person}
and finds the function it's looking for.
\end{itemize}
\figpdf{figures/oop-inheritance.pdf}{Object-Oriented Inheritance}{f:oop-inheritance}
\section{Exercises}\label{s:oop-exercises}
\exercise{Delays}
Define a class called \texttt{Delay} whose \texttt{call} method always returns
the value given in the \emph{previous} call:
\begin{minted}{js}
const example = new Delay('a')
for (let value of ['b', 'c', 'd']) {
console.log(value, '->', example.call(value))
}
\end{minted}
\begin{minted}{text}
b -> a
c -> b
d -> c
\end{minted}
A class like \texttt{Delay} is sometimes called \gref{g:stateful}{stateful},
since it remembers its state from call to call.
\exercise{Filtering}
Define a class called \texttt{Filter} whose \texttt{call} method returns \texttt{null}
if its input matches one of the values given to its constructor,
or the input as output otherwise:
\begin{minted}{js}
const example = new Filter('a', 'e', 'i', 'o', 'u')
for (let value of ['a', 'b', 'c', 'd', 'e']) {
console.log(value, '->', example.call(value))
}
\end{minted}
\begin{minted}{text}
a -> null
b -> b
c -> c
d -> d
e -> null
\end{minted}
A class like \texttt{Filter} is sometimes called \gref{g:stateless}{stateless},
since it does not remember its state from call to call.
\exercise{Pipelines}
Define a class called \texttt{Pipeline}
whose constructor takes one or more objects with a single-parameter \texttt{call} method,
and whose own \texttt{call} method passes a value through each of them in turn.
If any of the components' \texttt{call} methods returns \texttt{null},
\texttt{Pipeline} stops immediately and returns \texttt{null}.
\begin{minted}{js}
const example = new Pipeline(new Filter('a', 'e', 'i', 'o', 'u'),
new Delay('a'))
for (let value of ['a' ,'b', 'c', 'd', 'e']) {
console.log(value, '->', example.call(value))
}
\end{minted}
\begin{minted}{text}
a -> null
b -> a
c -> b
d -> c
e -> null
\end{minted}
\exercise{Active Expressions}
Consider this class:
\begin{minted}{js}
class Active {
constructor (name, transform) {
this.name = name
this.transform = transform
this.subscribers = []
}
subscribe (someone) {
this.subscribers.push(someone)
}
update (input) {
console.log(this.name, 'got', input)
const output = this.transform(input)
for (let s of this.subscribers) {
s.update(output)
}
}
}
\end{minted}
\noindent
and this program that uses it:
\begin{minted}{js}
const start = new Active('start', (x) => Math.min(x, 10))
const left = new Active('left', (x) => 2 * x)
const right = new Active('right', (x) => x + 1)
const final = new Active('final', (x) => x)
start.subscribe(left)
start.subscribe(right)
left.subscribe(final)
right.subscribe(final)
start.update(123)
\end{minted}
\begin{enumerate}
\item
Trace what happens when the last line of the program is called.
\item
Modify \texttt{Active} so that it calls \texttt{transform} \emph{if} that function was provided,
or a method \texttt{Active.transform} if a transformation function wasn't provided.
\item
Create a new class \texttt{Delay} whose \texttt{transform} method always returns the previous value.
(Its constructor will need to take an initial value as a parameter.)
\end{enumerate}
This pattern is called \gref{g:observer-observable}{observer/observable}.
\section*{Key Points}
\input{keypoints/oop}