Skip to content

Commit 71a235b

Browse files
committed
Add a generator example
1 parent 85eac5b commit 71a235b

1 file changed

Lines changed: 37 additions & 23 deletions

File tree

‎README.md‎

Lines changed: 37 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -314,10 +314,8 @@ create_menu(
314314
)
315315
```
316316

317-
318317
**[⬆ back to top](#table-of-contents)**
319318

320-
321319
### Functions should do one thing
322320
This is by far the most important rule in software engineering. When functions do more
323321
than one thing, they are harder to compose, test, and reason about. When you can isolate
@@ -326,33 +324,49 @@ cleaner. If you take nothing else away from this guide other than this, you'll b
326324
of many developers.
327325

328326
**Bad:**
329-
```php
330-
function emailClients($clients) {
331-
foreach ($clients as $client) {
332-
$clientRecord = $db->find($client);
333-
if ($clientRecord->isActive()) {
334-
email($client);
335-
}
336-
}
337-
}
327+
```python
328+
329+
def email_clients(clients: List[Client]):
330+
"""Filter active clients and send them an email.
331+
"""
332+
for client in clients:
333+
if client.active:
334+
email(client)
338335
```
339336

340337
**Good**:
341-
```php
342-
function emailClients($clients) {
343-
$activeClients = activeClients($clients);
344-
array_walk($activeClients, 'email');
345-
}
338+
```python
339+
def get_active_clients(clients: List[Client]) -> List[Client]:
340+
"""Filter active clients.
341+
"""
342+
return [client for client in clients if client.active]
346343

347-
function activeClients($clients) {
348-
return array_filter($clients, 'isClientActive');
349-
}
350344

351-
function isClientActive($client) {
352-
$clientRecord = $db->find($client);
353-
return $clientRecord->isActive();
354-
}
345+
def email_clients(clients: List[Client, ...]) -> None:
346+
"""Send an email to a given list of clients.
347+
"""
348+
for client in clients:
349+
email(client)
355350
```
351+
352+
Do you see an opportunity for using generators now?
353+
354+
**Even better**
355+
```python
356+
def active_clients(clients: List[Client]) -> Generator[Client]:
357+
"""Only active clients.
358+
"""
359+
return (client for client in clients if client.active)
360+
361+
362+
def email_client(clients: Iterator[Client]) -> None:
363+
"""Send an email to a given list of clients.
364+
"""
365+
for client in clients:
366+
email(client)
367+
```
368+
369+
356370
**[⬆ back to top](#table-of-contents)**
357371

358372
### Function names should say what they do

0 commit comments

Comments
 (0)