|
| 1 | +from dataclasses import dataclass |
| 2 | +from typing import Optional |
| 3 | + |
| 4 | +# Before refactoring - unclear types |
| 5 | +def process_user_data(data): |
| 6 | + name = data[0] |
| 7 | + age = data[1] |
| 8 | + email = data[2] if len(data) > 2 else None |
| 9 | + |
| 10 | + if age < 18: |
| 11 | + return None |
| 12 | + |
| 13 | + return f"{name} ({age}): {email or 'no email'}" |
| 14 | + |
| 15 | + |
| 16 | +# After refactoring - clear types |
| 17 | +@dataclass |
| 18 | +class User: |
| 19 | + name: str |
| 20 | + age: int |
| 21 | + email: Optional[str] = None |
| 22 | + |
| 23 | +def is_adult(user: User) -> bool: |
| 24 | + return user.age >= 18 |
| 25 | + |
| 26 | +def format_user_info(user: User) -> str: |
| 27 | + email_str = user.email if user.email else "no email" |
| 28 | + return f"{user.name} ({user.age}): {email_str}" |
| 29 | + |
| 30 | +def process_user(user: User) -> Optional[str]: |
| 31 | + if not is_adult(user): |
| 32 | + return None |
| 33 | + return format_user_info(user) |
| 34 | + |
| 35 | + |
| 36 | +# Testing old version |
| 37 | +print(process_user_data(("Alice", 25, "alice@example.com"))) |
| 38 | +print(process_user_data(("Bob", 16))) |
| 39 | + |
| 40 | +# Testing new version |
| 41 | +user1 = User("Alice", 25, "alice@example.com") |
| 42 | +user2 = User("Bob", 16) |
| 43 | + |
| 44 | +print(process_user(user1)) |
| 45 | +print(process_user(user2)) |
| 46 | + |
| 47 | + |
| 48 | +# Another example |
| 49 | +def get_value(key: str, data: dict[str, int]) -> Optional[int]: |
| 50 | + return data.get(key) |
| 51 | + |
| 52 | +sample_data = {"a": 1, "b": 2} |
| 53 | +result = get_value("a", sample_data) |
| 54 | +if result is not None: |
| 55 | + print(f"Found: {result}") |
0 commit comments