► Understanding Code Organization
Code organization is about structuring your programs in a clear, maintainable way. Good organization makes code easier to read, debug, and modify. It’s like keeping your workspace tidy – everything has its place.
► Real-World Analogy
Think of code organization like organizing a kitchen:
» Related items stored together (functions in modules)
» Clear labels on containers (meaningful names)
» Frequently used items within easy reach (common functions at top)
» Clean counter space (remove unused code)
» Recipe cards organized by category (group related functions)
► Key Concepts
✓ Meaningful names: Use descriptive variable and function names
✓ Single responsibility: Each function does one thing well
✓ DRY principle: Don’t Repeat Yourself
✓ Comments: Explain why, not what
✓ Consistent style: Follow naming conventions
■ Code Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
# Bad: Unclear names and messy structure def f(x, y): return x * y + 10 # Good: Clear names and structure def calculate_total_price(quantity, unit_price): """Calculate total price with tax.""" subtotal = quantity * unit_price TAX_RATE = 0.10 total = subtotal + (subtotal * TAX_RATE) return total # Group related functions class Calculator: def add(self, a, b): return a + b def subtract(self, a, b): return a - b # Constants at top MAX_RETRIES = 3 DEFAULT_TIMEOUT = 30 # Main logic def main(): calc = Calculator() result = calc.add(5, 3) print(f"Result: {result}") if __name__ == "__main__": main() |
