Skip to content

Commit 374f710

Browse files
committed
Add an extra case to the 'Avoid Side Effects' section
1 parent e94c4b9 commit 374f710

1 file changed

Lines changed: 22 additions & 5 deletions

File tree

README.md

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -529,9 +529,9 @@ def create_temp_file(name: str) -> None:
529529
### Avoid side effects
530530

531531
A function produces a side effect if it does anything other than take a value in
532-
and return another value or values. A side effect could be writing to a file,
533-
modifying some global variable, or accidentally wiring all your money to a
534-
stranger.
532+
and return another value or values. For example, a side effect could be writing
533+
to a file, modifying some global variable, or accidentally wiring all your money
534+
to a stranger.
535535

536536
Now, you do need to have side effects in a program on occasion - for example, like
537537
in the previous example, you might need to write to a file. In these cases, you
@@ -541,8 +541,8 @@ several functions and classes that write to a particular file - rather, have one
541541

542542
The main point is to avoid common pitfalls like sharing state between objects
543543
without any structure, using mutable data types that can be written to by anything,
544-
and not centralizing where your side effects occur. If you can do this, you will be
545-
happier than the vast majority of other programmers.
544+
or using an instance of a class, and not centralizing where your side effects occur.
545+
If you can do this, you will be happier than the vast majority of other programmers.
546546

547547
**Bad:**
548548

@@ -572,5 +572,22 @@ print(name) # 'Ryan McDermott'
572572
print(new_name) # ['Ryan', 'McDermott']
573573
```
574574

575+
**Also good**
576+
```python
577+
class Person:
578+
name: str
579+
580+
def __init__(self, name):
581+
self.name = name
582+
583+
@property
584+
def name_as_first_and_last(self):
585+
return self.name.split()
586+
587+
person = Person('Ryan McDermott')
588+
print(person.name) # 'Ryan McDermott'
589+
print(person.name_as_first_and_last) # ['Ryan', 'McDermott']
590+
```
591+
575592
**[⬆ back to top](#table-of-contents)**
576593

0 commit comments

Comments
 (0)