Slide 1

Slide 1 text

“A poet is, before anything else, a person who is passionately in love with language.” W. H. Auden by Erik Rose Poetic APIs Designing

Slide 2

Slide 2 text

“A poet is, before anything else, a person who is passionately in love with language.” W. H. Auden by Erik Rose programmer ^ Poetic APIs Designing

Slide 3

Slide 3 text

“The limits of my language are the limits of my world.” Ludwig Wittgenstein Sapir-Whorf

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.” Martin Fowler Intellectual Intelligibility

Slide 6

Slide 6 text

req = urllib2.Request(gh_url) password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password( None, 'https://api.github.com', 'user', 'pass') auth_manager = urllib2.HTTPBasicAuthHandler(password_manager) opener = urllib2.build_opener(auth_manager) urllib2.install_opener(opener) handler = urllib2.urlopen(req) print handler.getcode()

Slide 7

Slide 7 text

req = urllib2.Request(gh_url) password_manager = urllib2.HTTPPasswordMgrWithDefaultRealm() password_manager.add_password( None, 'https://api.github.com', 'user', 'pass') auth_manager = urllib2.HTTPBasicAuthHandler(password_manager) opener = urllib2.build_opener(auth_manager) urllib2.install_opener(opener) handler = urllib2.urlopen(req) print handler.getcode() r = requests.get('https://api.github.com', auth=('user', 'pass')) print r.status_code

Slide 8

Slide 8 text

1 Don’t Be An Architecture Astronaut “It’s hard to make predictions, especially about the future.” Robert Storm Petersen

Slide 9

Slide 9 text

No content

Slide 10

Slide 10 text

The best libraries are extracted, not invented.

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

No content

Slide 13

Slide 13 text

def terminal_codes(self, stream): capabilities = ['bold', 'sc', 'rc', 'sgr0', 'el'] if hasattr(stream, 'fileno') and isatty(stream.fileno()): # Explicit args make setupterm() work even when -s is passed: setupterm(None, stream.fileno()) # so things like tigetstr() work codes = dict((x, tigetstr(x)) for x in capabilities) cup = tigetstr('cup') codes['cup'] = lambda line, column: tparm(cup, line, column) else: # If you're crazy enough to pipe this to a file or something, # don't output terminal codes: codes = defaultdict(lambda: '', cup=lambda line, column: '') return codes ... self._codes = terminal_codes(stdout) ... class AtLine(object): def __enter__(self): """Save position and move to progress bar, col 1.""" self.stream.write(self._codes['sc']) # save position self.stream.write(self._codes['cup'](self.line, 0)) def __exit__(self, type, value, tb): self.stream.write(self._codes['rc']) # restore position ... print self._codes['bold'] + results + self._codes['sgr0']

Slide 14

Slide 14 text

def terminal_codes(self, stream): capabilities = ['bold', 'sc', 'rc', 'sgr0', 'el'] if hasattr(stream, 'fileno') and isatty(stream.fileno()): # Explicit args make setupterm() work even when -s is passed: setupterm(None, stream.fileno()) # so things like tigetstr() work codes = dict((x, tigetstr(x)) for x in capabilities) cup = tigetstr('cup') codes['cup'] = lambda line, column: tparm(cup, line, column) else: # If you're crazy enough to pipe this to a file or something, # don't output terminal codes: codes = defaultdict(lambda: '', cup=lambda line, column: '') return codes ... self._codes = terminal_codes(stdout) ... class AtLine(object): def __enter__(self): """Save position and move to progress bar, col 1.""" self.stream.write(self._codes['sc']) # save position self.stream.write(self._codes['cup'](self.line, 0)) def __exit__(self, type, value, tb): self.stream.write(self._codes['rc']) # restore position ... print self._codes['bold'] + results + self._codes['sgr0']

Slide 15

Slide 15 text

Tasks

Slide 16

Slide 16 text

Tasks Print some text with formatting.

Slide 17

Slide 17 text

Tasks Print some text with formatting. Print some text at a location, then snap back.

Slide 18

Slide 18 text

Language Constructs

Slide 19

Slide 19 text

Language Constructs Functions, arguments, keyword arguments

Slide 20

Slide 20 text

Language Constructs Functions, arguments, keyword arguments Decorators

Slide 21

Slide 21 text

Language Constructs Functions, arguments, keyword arguments Decorators Context managers

Slide 22

Slide 22 text

Language Constructs Functions, arguments, keyword arguments Decorators Context managers Classes (really more of an implementation detail)

Slide 23

Slide 23 text

Patterns, Protocols, Interfaces, and Conventions å Language Constructs Functions, arguments, keyword arguments Decorators Context managers Classes (really more of an implementation detail)

Slide 24

Slide 24 text

Sequences Patterns, Protocols, Interfaces, and Conventions å Language Constructs Functions, arguments, keyword arguments Decorators Context managers Classes (really more of an implementation detail)

Slide 25

Slide 25 text

Sequences Iterators Patterns, Protocols, Interfaces, and Conventions å Language Constructs Functions, arguments, keyword arguments Decorators Context managers Classes (really more of an implementation detail)

Slide 26

Slide 26 text

Sequences Iterators Mappings Patterns, Protocols, Interfaces, and Conventions å Language Constructs Functions, arguments, keyword arguments Decorators Context managers Classes (really more of an implementation detail)

Slide 27

Slide 27 text

2 “Think like a wise man, but communicate in the language of the people.” William Butler Yeats Consistency

Slide 28

Slide 28 text

No content

Slide 29

Slide 29 text

get(key, default) is better than fetch(default, key)

Slide 30

Slide 30 text

Tasks Print some text at a location, then snap back. Print some text with formatting.

Slide 31

Slide 31 text

Tasks Print some text at a location, then snap back. Print some text with formatting. print_at('Hello world', 10, 2) with location(10, 2): print 'Hello world' for thing in range(10): print thing

Slide 32

Slide 32 text

Tasks Print some text at a location, then snap back. Print some text with formatting. print_formatted('Hello world', 'red', 'bold') print color('Hello world', 'red', 'bold') print color('Hello world') print red(bold('Hello') + 'world') print codes['red'] + codes['bold'] + \ 'Hello world' + codes['normal'] print '{t.red}Hi{t.bold}Mom{t.normal}'.format(t=terminal) print terminal.red_bold + 'Hello world' + terminal.normal

Slide 33

Slide 33 text

Tasks Print some text at a location, then snap back. Print some text with formatting. print_formatted('Hello world', 'red', 'bold') print color('Hello world', 'red', 'bold') print color('Hello world') print red(bold('Hello') + 'world') print codes['red'] + codes['bold'] + \ 'Hello world' + codes['normal'] print '{t.red}Hi{t.bold}Mom{t.normal}'.format(t=terminal) print terminal.red_bold + 'Hello world' + terminal.normal

Slide 34

Slide 34 text

Tasks Print some text at a location, then snap back. Print some text with formatting. print_formatted('Hello world', 'red', 'bold') print color('Hello world', 'red', 'bold') print color('Hello world') print red(bold('Hello') + 'world') print codes['red'] + codes['bold'] + \ 'Hello world' + codes['normal'] print '{t.red}Hi{t.bold}Mom{t.normal}'.format(t=terminal) print terminal.red_bold + 'Hello world' + terminal.normal

Slide 35

Slide 35 text

Tasks Print some text at a location, then snap back. Print some text with formatting. print_formatted('Hello world', 'red', 'bold') print color('Hello world', 'red', 'bold') print color('Hello world') print red(bold('Hello') + 'world') print codes['red'] + codes['bold'] + \ 'Hello world' + codes['normal'] print '{t.red}Hi{t.bold}Mom{t.normal}'.format(t=terminal) print terminal.red_bold + 'Hello world' + terminal.normal

Slide 36

Slide 36 text

from blessings import Terminal t = Terminal() print t.red_bold + 'Hello world' + t.normal print t.red_on_white + 'Hello world' + t.normal print t.underline_red_on_green + 'Hello world' + t.normal

Slide 37

Slide 37 text

from blessings import Terminal t = Terminal() print t.red_bold + 'Hello world' + t.normal print t.red_on_white + 'Hello world' + t.normal print t.underline_red_on_green + 'Hello world' + t.normal Article.objects.filter(tag__in=['color_red', 'color_blue']) Article.objects.filter(tag__contains='color')

Slide 38

Slide 38 text

Consistency warning signs

Slide 39

Slide 39 text

Consistency warning signs Frequent references to your docs or source

Slide 40

Slide 40 text

Consistency warning signs Frequent references to your docs or source Feeling syntactically clever

Slide 41

Slide 41 text

3 “The finest language is mostly made up of simple, unimposing words.” George Eliot Brevity

Slide 42

Slide 42 text

from blessings import Terminal term = Terminal() print term.bold + 'I am bold!' + term.normal

Slide 43

Slide 43 text

from blessings import Terminal term = Terminal() print term.bold + 'I am bold!' + term.normal print term.bold('I am bold!')

Slide 44

Slide 44 text

from blessings import Terminal term = Terminal() print term.bold + 'I am bold!' + term.normal print term.bold('I am bold!')

Slide 45

Slide 45 text

from blessings import Terminal term = Terminal() print term.bold + 'I am bold!' + term.normal print '{t.bold}Very {t.red}emphasized{t.normal}'.format(t=term) print term.bold('I am bold!')

Slide 46

Slide 46 text

Brevity warning signs

Slide 47

Slide 47 text

Brevity warning signs Copying and pasting when writing against your API

Slide 48

Slide 48 text

Brevity warning signs Copying and pasting when writing against your API Typing something irrelevant while grumbling “Why can’t it just assume the obvious thing?”

Slide 49

Slide 49 text

Brevity warning signs Copying and pasting when writing against your API Typing something irrelevant while grumbling “Why can’t it just assume the obvious thing?” Long arg lists, suggesting a lack of sane defaults

Slide 50

Slide 50 text

4 “Perfection is achieved not when there is nothing left to add but when there is nothing left to take away.” Antoine de Saint-Exupery Composability

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

print_formatted('Hello world', 'red', 'bold')

Slide 53

Slide 53 text

print_formatted('Hello world', 'red', 'bold') print_formatted('Hello world', 'red', 'bold', out=some_file)

Slide 54

Slide 54 text

print_formatted('Hello world', 'red', 'bold') print_formatted('Hello world', 'red', 'bold', out=some_file) print formatted('Hello world', 'red', 'bold')

Slide 55

Slide 55 text

Composabilty warning signs

Slide 56

Slide 56 text

Composabilty warning signs Classes with lots of state

Slide 57

Slide 57 text

Composabilty warning signs class ElasticSearch(object): """ An object which manages connections to elasticsearch and acts as a go-between for API calls to it""" def index(self, index, doc_type, doc, id=None, force_insert=False, query_params=None): """Put a typed JSON document into a specific index to make it searchable.""" def search(self, query, **kwargs): """Execute a search query against one or more indices and get back search hits.""" def more_like_this(self, index, doc_type, id, mlt_fields, body='', query_params=None): """Execute a "more like this" search query against one or more fields and get back search hits.""" . . . Classes with lots of state

Slide 58

Slide 58 text

Composabilty warning signs class ElasticSearch(object): """ An object which manages connections to elasticsearch and acts as a go-between for API calls to it""" def index(self, index, doc_type, doc, id=None, force_insert=False, query_params=None): """Put a typed JSON document into a specific index to make it searchable.""" def search(self, query, **kwargs): """Execute a search query against one or more indices and get back search hits.""" def more_like_this(self, index, doc_type, id, mlt_fields, body='', query_params=None): """Execute a "more like this" search query against one or more fields and get back search hits.""" . . . class PenaltyBox(object): """A thread-safe bucket of servers (or other things) that may have downtime.""" def get(self): """Return a random server and a bool indicating whether it was from the dead list.""" def mark_dead(self, server): """Guarantee that this server won't be returned again until a period of time has passed, unless all servers are dead.""" def mark_live(self, server): """Move a server from the dead list to the live one.""" Classes with lots of state

Slide 59

Slide 59 text

Composabilty warning signs Classes with lots of state Deep inheritance hierarchies

Slide 60

Slide 60 text

Composabilty warning signs Classes with lots of state Deep inheritance hierarchies Violations of the Law of Demeter

Slide 61

Slide 61 text

Composabilty warning signs Classes with lots of state Deep inheritance hierarchies Violations of the Law of Demeter Mocking in tests

Slide 62

Slide 62 text

Composabilty warning signs print_formatted('Hello world', 'red', 'bold') Classes with lots of state Deep inheritance hierarchies Violations of the Law of Demeter Mocking in tests

Slide 63

Slide 63 text

Composabilty warning signs print_formatted('Hello world', 'red', 'bold') print formatted('Hello world', 'red', 'bold') Classes with lots of state Deep inheritance hierarchies Violations of the Law of Demeter Mocking in tests

Slide 64

Slide 64 text

Composabilty warning signs Classes with lots of state Deep inheritance hierarchies Violations of the Law of Demeter Mocking in tests Options

Slide 65

Slide 65 text

5 “All the great things are simple, and many can be expressed in a single word…” Sir Winston Churchill Plain Data

Slide 66

Slide 66 text

No content

Slide 67

Slide 67 text

Slide 68

Slide 68 text

Slide 69

Slide 69 text

✚ ✚

Slide 70

Slide 70 text

RawConfigParser.parse(string) ✚ ✚

Slide 71

Slide 71 text

RawConfigParser.parse(string) charming_parser.parse(file_contents('some_file.ini')) ✚ ✚

Slide 72

Slide 72 text

class Node(dict): """A wrapper around a native Reflect.parse dict providing some convenience methods and some caching of expensive computations"""

Slide 73

Slide 73 text

class Node(dict): """A wrapper around a native Reflect.parse dict providing some convenience methods and some caching of expensive computations""" def walk_up(self): """Yield each node from here to the root of the tree, starting with myself.""" node = self while node: yield node node = node.get('_parent')

Slide 74

Slide 74 text

class Node(dict): """A wrapper around a native Reflect.parse dict providing some convenience methods and some caching of expensive computations""" def walk_up(self): """Yield each node from here to the root of the tree, starting with myself.""" node = self while node: yield node node = node.get('_parent') def nearest_scope_holder(self): """Return the nearest node that can have its own scope, potentially including myself. This will be either a FunctionDeclaration or a Program (for now). """ return first(n for n in self.walk_up() if n['type'] in ['FunctionDeclaration', 'Program'])

Slide 75

Slide 75 text

Plain Data warning signs

Slide 76

Slide 76 text

Plain Data warning signs Users immediately transforming your output to another format

Slide 77

Slide 77 text

Plain Data warning signs Users immediately transforming your output to another format Instantiating one object just to pass it to another

Slide 78

Slide 78 text

Plain Data warning signs Users immediately transforming your output to another format Instantiating one object just to pass it to another Rewriting language-provided things

Slide 79

Slide 79 text

6 “The bad teacher’s words fall on his pupils like harsh rain; the good teacher’s, as gently as dew.” Talmud: Ta’anith 7b Grooviness

Slide 80

Slide 80 text

6 Grooviness Wall Groove

Slide 81

Slide 81 text

Avoid nonsense representations.

Slide 82

Slide 82 text

{ "bool" : { "must" : { "term" : { "user" : "fred" } }, "must_not" : { "range" : { "age" : { "from" : 12, "to" : 21 } } }, "minimum_number_should_match" : 1, "boost" : 1.0 } } Avoid nonsense representations.

Slide 83

Slide 83 text

{ "bool" : { "must" : { "term" : { "user" : "fred" } }, "must_not" : { "range" : { "age" : { "from" : 12, "to" : 21 } } }, "minimum_number_should_match" : 1, "boost" : 1.0 } } frob*ator AND snork Avoid nonsense representations.

Slide 84

Slide 84 text

def search(self, q=None, body=None, indexes=None, doc_types=None): """Execute an elasticsearch query, and return the results.""" Old pyelasticsearch

Slide 85

Slide 85 text

def search(self, q=None, body=None, indexes=None, doc_types=None): """Execute an elasticsearch query, and return the results.""" Old pyelasticsearch search(q='frob*ator AND snork', body={'some': 'query'})

Slide 86

Slide 86 text

def search(self, q=None, body=None, indexes=None, doc_types=None): """Execute an elasticsearch query, and return the results.""" Old pyelasticsearch search(q='frob*ator AND snork', body={'some': 'query'}) search()

Slide 87

Slide 87 text

def search(self, q=None, body=None, indexes=None, doc_types=None): """Execute an elasticsearch query, and return the results.""" Old pyelasticsearch search(q='frob*ator AND snork', body={'some': 'query'}) search() ✚

Slide 88

Slide 88 text

def search(self, q=None, body=None, indexes=None, doc_types=None): """Execute an elasticsearch query, and return the results.""" Old pyelasticsearch search(q='frob*ator AND snork', body={'some': 'query'}) search() ✚ def search(self, query, indexes=None, doc_types=None): """Execute an elasticsearch query, and return the results.""" New pyelasticsearch

Slide 89

Slide 89 text

def search(self, q=None, body=None, indexes=None, doc_types=None): """Execute an elasticsearch query, and return the results.""" Old pyelasticsearch search(q='frob*ator AND snork', body={'some': 'query'}) search() ✚ def search(self, query, indexes=None, doc_types=None): """Execute an elasticsearch query, and return the results.""" New pyelasticsearch Fail shallowly.

Slide 90

Slide 90 text

Resource acquisition is initialization.

Slide 91

Slide 91 text

Resource acquisition is initialization. class PoppableBalloon(object): """A balloon you can pop""" def __init__(self): self.air = 0 def fill(self, how_much): self.air = how_much

Slide 92

Slide 92 text

Resource acquisition is initialization. class PoppableBalloon(object): """A balloon you can pop""" def __init__(self): self.air = 0 def fill(self, how_much): self.air = how_much class PoppableBalloon(object): """A balloon you can pop""" def __init__(self, initial_fill): self.air = initial_fill def fill(self, how_much): self.air = how_much

Slide 93

Slide 93 text

Compelling examples

Slide 94

Slide 94 text

Compelling examples

Slide 95

Slide 95 text

Grooviness warning signs

Slide 96

Slide 96 text

Grooviness warning signs Representable nonsense

Slide 97

Slide 97 text

Grooviness warning signs Representable nonsense Invariants that aren’t

Slide 98

Slide 98 text

Grooviness warning signs Representable nonsense Invariants that aren’t Lack of a clear starting point

Slide 99

Slide 99 text

Grooviness warning signs Representable nonsense Invariants that aren’t Lack of a clear starting point Long, complicated documentation

Slide 100

Slide 100 text

7 “I wish it was easier to hurt myself.” Nobody, ever Safety

Slide 101

Slide 101 text

7 Safety Wall Groove

Slide 102

Slide 102 text

update things set frob=2 where frob=1;

Slide 103

Slide 103 text

update things set frob=2 where frob=1; update things set frob=2;

Slide 104

Slide 104 text

update things set frob=2 where frob=1; update things set frob=2; update things set frob=2 all;

Slide 105

Slide 105 text

update things set frob=2 where frob=1; update things set frob=2; update things set frob=2 all; rm *.pyc

Slide 106

Slide 106 text

update things set frob=2 where frob=1; update things set frob=2; update things set frob=2 all; rm *.pyc rm *

Slide 107

Slide 107 text

update things set frob=2 where frob=1; update things set frob=2; update things set frob=2 all; rm *.pyc rm * rm -f *

Slide 108

Slide 108 text

def delete(self, index, doc_type, id=None): """Delete a typed JSON document from a specific index based on its id."""

Slide 109

Slide 109 text

def delete(self, index, doc_type, id=None): """Delete a typed JSON document from a specific index based on its id."""

Slide 110

Slide 110 text

def delete(self, index, doc_type, id=None): """Delete a typed JSON document from a specific index based on its id.""" def delete(self, index, doc_type, id): """Delete a typed JSON document from a specific index based on its id.""" def delete_all(self, index, doc_type): """Delete all documents of the given doctype from an index."""

Slide 111

Slide 111 text

Exceptions > Return Values

Slide 112

Slide 112 text

Safety warning signs

Slide 113

Slide 113 text

Safety warning signs Docs that say “remember to…” or “make sure you…”

Slide 114

Slide 114 text

Safety warning signs Docs that say “remember to…” or “make sure you…” Surprisingly few people will blame themselves.

Slide 115

Slide 115 text

Architecture Astronautics ✖ Inventing rather than extracting Consistency ✖ Frequent references to your docs or source ✖ Feeling syntactically clever Brevity ✖ Copying and pasting when writing against your API ✖ Grumbling about having to hand- hold the API Plain Data ✖ Users immediately transforming your output to another format ✖ Rewriting language facilities ✖ Instantiating an object just to pass it Composability ✖ Classes with lots of state ✖ Deep inheritance hierarchies ✖ Violations of the Law of Demeter ✖ Mocking in tests ✖ Bolted-on options Grooviness ✖ Nonsense states ✖ Invariants that aren’t ✖ Lack of a clear introductory path ✖ Complicated documentation Safety ✖ Docs that say “make sure you…” ✖ Destructive actions without walls Design Smell Checklist

Slide 116

Slide 116 text

Compactness Brevity Non- astronautics Consistency Composability Plain Data Grooviness Safety Fractalness Modularity Small interfaces between parts Flexibility Decoupling Memorability Encapsulation Minimalism Do only what’s needed. Orthogonality contributes to Key:

Slide 117

Slide 117 text

Compactness Brevity Non- astronautics Consistency Composability Plain Data Grooviness Safety Fractalness Modularity Small interfaces between parts Flexibility Decoupling Memorability Encapsulation Minimalism Do only what’s needed. Orthogonality contributes to Key:

Slide 118

Slide 118 text

Lingual Compactness Brevity Non- astronautics Consistency Composability Plain Data Grooviness Safety Fractalness Modularity Small interfaces between parts Flexibility Decoupling Memorability Encapsulation Minimalism Do only what’s needed. Orthogonality contributes to Key:

Slide 119

Slide 119 text

Lingual Mathematical Compactness Brevity Non- astronautics Consistency Composability Plain Data Grooviness Safety Fractalness Modularity Small interfaces between parts Flexibility Decoupling Memorability Encapsulation Minimalism Do only what’s needed. Orthogonality contributes to Key:

Slide 120

Slide 120 text

Lingual Mathematical Compactness Brevity Non- astronautics Consistency Composability Plain Data Grooviness Safety Fractalness Modularity Small interfaces between parts Flexibility Decoupling Memorability Encapsulation Minimalism Do only what’s needed. Orthogonality contributes to Key: Lingual

Slide 121

Slide 121 text

Lingual Mathematical Compactness Brevity Non- astronautics Consistency Composability Plain Data Grooviness Safety Fractalness Modularity Small interfaces between parts Flexibility Decoupling Memorability Encapsulation Minimalism Do only what’s needed. Orthogonality contributes to Key: Lingual Mathematical

Slide 122

Slide 122 text

twitter: ErikRose www.grinchcentral.com [email protected] Thank You