This repository has been archived by the owner on May 23, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
slides
658 lines (537 loc) · 12.4 KB
/
slides
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
Overcoming Our Obsession With Stringly-Typed Ruby
!TITLE
Overcoming Our Obsession With Stringly-Typed Ruby
Dave Copeland · @davetron5000
http://www.naildrivin5.com · http://technology.stitchfix.com
!IMAGE
images/cover.png
!IMAGE
images/dccar2.jpg
!TITLE
Overcoming Our Obsession With <br><i>Stringly-Typed</i> Ruby
!SECTION
Stringly-Typed
From @codinghorror's “New Programmer Jargon”
<a href="http://blog.codinghorror.com/new-programming-jargon/">http://blog.codinghorror.com/new-programming-jargon/</a>
!QUOTE
A riff on “strongly typed”.
Used to describe an implementation that needlessly relies on strings when programmer & refactor-friendly options are available.
!SECTION
A tale of two zip codes
U.S. postal codes
aka "Zip Codes"
!BULLETS
Zip Codes
* Five Digits, e.g. 90210
* Map to an area of the U.S.
!IMAGE
images/zipcode_map.png
!BULLETS
Simple App
* Store addresses in a DB
* Send letters to an address
!CODE: language=ruby, callout=2,3,4
module ThirdPartyMailingService
def self.find_letter(letter_id)
# ...
end
class Letter
def mail!(street,city,state,zip_code)
# ...
end
end
end
!CODE: language=ruby, callout=6,7,8,9,10
module ThirdPartyMailingService
def self.find_letter(letter_id)
# ...
end
class Letter
def mail!(street,city,state,zip_code)
# ...
end
end
end
!CODE: language=sql
create table addresses(
id int not null,
street varchar(256) not null,
city varchar(256) not null,
state char(2) not null,
zip_code char(5) not null
)
!CODE: language=ruby, callout=5,6
class AddressReader
def read_new_address
puts "Enter your address"
puts "street?"
street = gets
puts "city?"
city = gets
puts "state?"
state = gets
puts "zip code?"
zip_code = gets
id = $database.insert_into(:addresses,
street: street,
city: city,
state: state,
zip_code: zip_code)
puts "Created address #{id}"
end
end
!CODE: language=ruby, callout=17,18,19,20,21
class AddressReader
def read_new_address
puts "Enter your address"
puts "street?"
street = gets
puts "city?"
city = gets
puts "state?"
state = gets
puts "zip code?"
zip_code = gets
id = $database.insert_into(:addresses,
street: street,
city: city,
state: state,
zip_code: zip_code)
puts "Created address #{id}"
end
end
!CODE: language=ruby, callout=3
class LetterSender
def send_letter(letter_id,address_hash)
letter = ThirdPartyMailingService.find_letter(letter_id)
letter.mail!(address_hash[:street],
address_hash[:city],
address_hash[:state],
address_hash[:zip_code])
end
end
!CODE: language=ruby, callout=4,5,6,7
class LetterSender
def send_letter(letter_id,address_hash)
letter = ThirdPartyMailingService.find_letter(letter_id)
letter.mail!(address_hash[:street],
address_hash[:city],
address_hash[:state],
address_hash[:zip_code])
end
end
!CODE: language=ruby, callout=3,4
class Mailer
def send_letter(address_id,letter_id)
address_hash = $database.select_from(:addresses,
:id => address_id)
LetterSender.new.send_letter(letter_id, to: address_hash)
puts "Letter ##{letter_id} sent to"
puts address_hash[:street]
puts "#{address_hash[:city], #{address_hash[:state]}, #{address_hash[:zip_code]}"
end
end
Mailer.new.send_letter(ARGV[0].to_i, ARGV[1].to_i)
!CODE: language=ruby, callout=5
class Mailer
def send_letter(address_id,letter_id)
address_hash = $database.select_from(:addresses,
:id => address_id)
LetterSender.new.send_letter(letter_id, to: address_hash)
puts "Letter ##{letter_id} sent to"
puts address_hash[:street]
puts "#{address_hash[:city], #{address_hash[:state]}, #{address_hash[:zip_code]}"
end
end
Mailer.new.send_letter(ARGV[0].to_i, ARGV[1].to_i)
!COMMANDLINE
> ./store_address.rb
street?
> 45 S. Fair Oaks Ave
city?
> Beverley Hills
state?
> CA
zip?
> 90210
You created address 42
!COMMANDLINE
> ./send_letter.rb 42 12
Letter #12 sent to
45 S. Fair Oaks Ave
Beverley Hills, CA 90210
!COMMANDLINE
> ./store_address.rb
street?
> 1675 E Altadena Dr
city?
> Altadena
state?
> CA
zip?
> WALSH
You created address 43
!COMMANDLINE
> ./send_letter.rb 43 12
Letter #12 sent to
1675 E Altadena Dr
Altadena, CA WALSH
!NORMAL
Oops
!NORMAL
Must be a problem reading input!
!CODE: language=ruby, callout=3,4,5
zip_code = gets
unless zip_code =~ /^[0-9]{5}$/
raise "not a zip code"
end
!CODE: language=sql
INSERT INTO
addresses(street,city,state,zip)
VALUES
('1675 E Altadena Dr'
'Altadena',
'CA',
'WALSH')
!NORMAL
Oh! Oh!
A problem in our database design!
!CODE: language=sql, callout=5,6,7
ALTER TABLE
addresses
ADD CONSTRAINT
looks_like_a_zipcode
CHECK (
(zip ~* '^[0-9]{5}$')
)
!CODE: language=ruby
LetterSender.new.send_letter(letter_id,
street: '1675 E Altadena Dr'
city: 'Altadena',
state: 'CA',
zip_code: 'WALSH')
!IMAGE
images/buzz.png
!SECTION
This is not how to build a maintainable system
!IMAGE
images/loose_boundaries.png
!SECTION
Boundaries
!NORMAL
What's coming and what's going
!IMAGE
images/method.png
!IMAGE
images/strings_and_hashes.png
!SECTION
Data Types
!BULLETS
Data Types
* Possible Values
* Allowed Operations
* What they mean
!FREEFORM
<table>
<thead>
<th></th>
<th>String</th>
<th>Zip Code</th>
</thead>
<tbody>
<tr>
<th>Possible values</th>
<td>Anything</td>
<td>Five Digits</td>
</tr>
<tr>
<th>Operations</th>
<td>A ton</td>
<td>Pretty much none</td>
</tr>
<tr>
<th>What They Mean</th>
<td>Anything</td>
<td>Location in the U.S.</td>
</tr>
</tbody>
</table>
!IMAGE
images/strong_boundaries.png
!CODE: language=ruby
class ZipCode
def initialize(string)
@raw_zipcode = string
end
end
!CODE: language=ruby
class ZipCode
def initialize(string)
unless string =~ /^\d\d\d\d\d$/
raise 'invalid zipcode'
end
@raw_zipcode = string
end
end
!CODE: language=ruby
zip1 = ZipCode.new("90210")
zip2 = ZipCode.new("WALSH")
# => boom
# zip2 never gets assigned
!CODE: language=ruby
class ZipCode
def raw_zipcode
@raw_zipcode
end
end
!IMAGE
images/strong_boundaries.png
!BULLETS
Design Activity
* What problem am I solving?
* Push code around to solve it
* Define boundaries using data types
!SECTION
How do we publicize these boundaries?
!BULLETS
Conventions
* Underscorize the classname, e.g. <code>zip_code</code>
* Suffix with underscorized, e.g. <code>sender_zip_code</code>
* Document public methods
!CODE: language=ruby
class FooBar
# zip_code:: instance of ZipCode to geolocate
def geolocate(zip_code)
end
# Returns a ZipCode nearest the given lat and long
def nearest_zip_code(lat,long)
end
private
def center_point(zip_code)
end
end
!SECTION
Can we enforce this?
!CODE: language=ruby, callout=3
class FooBar
def geolocate(zip_code)
unless zip_code.is_a?(ZipCode)
raise ArgumentError, "must be a ZipCode"
end
# ...
end
end
!CODE: language=ruby, callout=3
class FooBar
def geolocate(zip_code)
unless zip_code.instance_of?(ZipCode)
raise ArgumentError, "must be a ZipCode"
end
# ...
end
end
!CODE: language=ruby, callout=3
class FooBar
def geolocate(zip_code)
unless zip_code.respond_to?(:raw_zipcode)
raise ArgumentError, "must implement #raw_zipcode"
end
# ...
end
end
!CODE: language=ruby, callout=4
class FooBarTest
def test_that_we_get_the_right_data_type
result = foo_bar.nearest_zip_code(lat,long)
assert result.is_a?(ZipCode),
"Got a #{result.class} instead :("
end
end
!SECTION
<strong>Should</strong> we?
!IMAGE
images/types_everywhere.png
!IMAGE
images/scala-logo.png
!BULLETS
Two Times You Might
* Risk
* Big Refactor
!BULLETS
Risk
* How often do we expect a bad type?
* What happens if a one does?
!BULLETS
Big Refactor (w/compiler)
* Change core types as needed
* Compile
* Fix the errors
!BULLETS
Big Refactor (no compiler)
* Change core types as needed
* Add explicit type checks
* Run tests
* Fix the errors
* Remove explicit type checks
!BULLETS
When The World Wants/Has Strings
* Protocols - Data Type → String
* Wrappers - String → Data Type
!SECTION
Protocols
<a href="http://www.confidentruby.com">www.confidentruby.com</a>
Chapter 4.2
!CODE: language=ruby
class ZipCode
def initialize(string)
unless string =~ /^\d\d\d\d\d$/
raise 'invalid zipcode'
end
@raw_zipcode = string
end
def raw_zipcode
@raw_zipcode
end
end
!COMMANDLINE
> zip = ZipCode.new("90210")
<ZipCode:0x007fb02d8b0968 @raw_zipcode="90210">
> puts zip
<ZipCode:0x007fb02d8b0968>
> puts "The zip is #{zip}"
The zip is <ZipCode:0x007fb02d8b0968>
!CODE: language=ruby
class ZipCode
alias to_s raw_zipcode
end
!COMMANDLINE
> puts "The zip is #{zip}"
The zip is 90210
> puts "The zip is " + zip
TypeError: no implicit conversion of ZipCode into String
from (irb):12:in `+'
from (irb):12
from /Users/davec/.rvm/rubies/ruby-2.1.0/bin/irb:11:in `<main>'
!CODE: language=ruby
class ZipCode
alias to_str raw_zipcode
end
!COMMANDLINE
> puts "The zip is " + zip
The zip is 90210
!CODE: language=html
<dt>ZipCode</dt>
<dd><%= zip_code %></dd>
!BULLETS
Non-String Goodies, too
* <code>to_a</code>
* <code>to_int</code>
* <code>to_h</code>
!SECTION
Wrappers
!CODE: language=ruby
class Mailer
def send_letter(address_id,letter_id)
address_hash = $database.select_from(:addresses,
:id => address_id)
LetterSender.new.send_letter(letter_id, to: address_hash)
end
end
!CODE: language=ruby, callout=3
class WrappingDatabase < SimpleDelegator
def convert(table: table, column: column, to: type)
@conversions[table][column] = type
end
end
$database = WrappingDatabase.new($database)
$database.convert table: :addresses,
column: :zip_code,
to: ZipCode
!CODE: language=ruby
class WrappingDatabase < SimpleDelegator
def select_from(table, where)
raw_results = __getobj__.select_from(table,where)
convert_results(table,raw_results)
end
end
!CODE: language=ruby
def convert_results(table,raw_results)
raw_results.map { |row_hash|
convert_row(table,row_hash)
}
end
!CODE: language=ruby
def convert_row(table,row_hash)
row_as_array = row_hash.map { |column,value|
new_value = if @conversions[table][column]
# e.g. ZipCode.new("90210")
@conversions[table][column].new(value)
else
value
end
[column,new_value]
}
row_as_array.to_h
end
!NORMAL
Active Record
!CODE: language=ruby
class Address < ActiveRecord::Base
serialize :zip_code, ZipCode
end
!CODE: language=ruby
class ZipCode
def self.load(raw_string)
self.new(raw_string)
end
def self.dump(zip_code)
zip_code.to_str
end
end
!CODE: language=none
address = Address.find(43) # has the bad zipcode
<ArgumentError "must be a ZipCode">
!NORMAL
Sequel
!CODE: language=ruby
require 'sequel/plugins/serialization'
Sequel::Plugins::Serialization.register_format(:zip_code_serialization,
->(zip_code) { zip_code.to_str },
->(raw_string) { ZipCode.new(raw_string) }
)
class Address < Sequel::Model
plugin :serialization
serialize_attributes :zip_code_serialization, :zip_code
end
!SECTION
Other Opportunites
!NORMAL
Email
<code>EmailAddress</code>, <code>VerifiedEmailAddress</code>
!COMMANDLINE
> "[email protected]" == "[email protected]"
=> false
> "[email protected]".downcase == "[email protected]".downcase #sigh
=> true
> EmailAddress.new("[email protected]") == EmailAddress.new("[email protected]")
=> true
!NORMAL
Prices
!COMMANDLINE
> third = Rational(1,3)
> (100 * third).to_f
33.333333333336
> Price.new(100).discount(third)
<Price value=33.33>
!NORMAL
Enumerated Types
State/Province, Status Codes, Error Codes
!SECTION
Use Data Types
Define Your Boundaries
Put Your Knowledge and Intent in Code
!FREEFORM
<h1>THANKS!</h1>
<h2><a href="#">Slides</a></h2>
<h3><a href="http://www.naildrivin5.com/blog">My Blog - http://www.naildrivin5.com/blog</a></h3>
<h4><a href="http://technology.stitchfix.com/jobs">Get A New Job at http://technology.stitchfix.com/jobs</a></h4>