Skip to content

Commit 01fb96a

Browse files
committed
Add methods-exercise1.md: advantages of using methods vs free functions
1 parent 21fdd0a commit 01fb96a

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

prep/methods-exercise1.md

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
Here are the advantages of using methods instead of free functions:
2+
3+
1. **Organization** - Methods are part of a class, so related code is organized together in one place.
4+
5+
2. **Access to object data** - Methods can directly access the object's attributes (like `person.age`). Free functions need the object passed as a parameter.
6+
7+
3. **Clearer intent** - When you see `person.is_adult()`, it's clear that you're asking "is this person an adult?" instead of `is_adult(person)`.
8+
9+
4. **Less parameter passing** - Methods use `self` automatically, so you don't need to pass the object as a parameter every time.
10+
11+
5. **Better grouping** - All actions for a `Person` are grouped together inside the `Person` class, not scattered around your code.
12+
13+
6. **Easier to maintain** - If you need to change how `is_adult()` works, you only need to update the method in one place inside the class.
14+
15+
7. **More readable** - `imran.is_adult()` is easier to read and understand than `is_adult(imran)`.
16+
17+
**Example comparison:**
18+
19+
```python
20+
# Free function (current approach)
21+
print(is_adult(imran))
22+
23+
# Method (better approach)
24+
print(imran.is_adult())
25+
```
26+
27+
The method version is clearer and more organized!

0 commit comments

Comments
 (0)