Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit71a235b

Browse files
committed
Add a generator example
1 parent85eac5b commit71a235b

File tree

1 file changed

+37
-23
lines changed

1 file changed

+37
-23
lines changed

‎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+
defemail_clients(clients: List[Client]):
330+
"""Filter active clients and send them an email.
331+
"""
332+
for clientin 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+
defget_active_clients(clients: List[Client]) -> List[Client]:
340+
"""Filter activeclients.
341+
"""
342+
return [clientfor clientin clientsif 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+
defemail_clients(clients: List[Client,...]) ->None:
346+
"""Send an email to a given list of clients.
347+
"""
348+
for clientin clients:
349+
email(client)
355350
```
351+
352+
Do you see an opportunity for using generators now?
353+
354+
**Even better**
355+
```python
356+
defactive_clients(clients: List[Client]) -> Generator[Client]:
357+
"""Only active clients.
358+
"""
359+
return (clientfor clientin clientsif client.active)
360+
361+
362+
defemail_client(clients: Iterator[Client]) ->None:
363+
"""Send an email to a given list of clients.
364+
"""
365+
for clientin 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)

[8]ページ先頭

©2009-2025 Movatter.jp