🏗️ Structure Your Code

Well-structured code is easier to understand, maintain, and debug. Good organization makes your projects scalable and helps other developers (including future you) work with your code effectively.

# Example of well-structured code organization

# config.py - Configuration constants
DATABASE_URL = "sqlite:///app.db"
API_TIMEOUT = 30
MAX_RETRIES = 3

# models.py - Data models
class User:
    def __init__(self, username: str, email: str):
        self.username = username
        self.email = email
        self.is_active = True
    
    def deactivate(self):
        """Deactivate the user account."""
        self.is_active = False

# services.py - Business logic
class UserService:
    def __init__(self):
        self.users = {}
    
    def create_user(self, username: str, email: str) -> User:
        """Create a new user."""
        if username in self.users:
            raise ValueError(f"User {username} already exists")
        
        user = User(username, email)
        self.users[username] = user
        return user
    
    def get_user(self, username: str) -> User:
        """Get user by username."""
        return self.users.get(username)

# main.py - Application entry point
def main():
    service = UserService()
    user = service.create_user("alice", "alice@example.com")
    print(f"Created user: {user.username}")

if __name__ == "__main__":
    main()

🎯 Understanding Code Structure

Good code structure follows clear patterns that make programs easier to navigate and understand.

Function Organization

# Good function structure and organization

def calculate_total_price(items, tax_rate=0.08, discount=0.0):
    """Calculate total price with tax and discount."""
    if not items:
        return 0.0
    
    subtotal = sum(item['price'] * item['quantity'] for item in items)
    discounted_total = subtotal * (1 - discount)
    final_total = discounted_total * (1 + tax_rate)
    
    return round(final_total, 2)

def validate_email(email):
    """Check if email format is valid."""
    if not email or '@' not in email:
        return False
    
    parts = email.split('@')
    if len(parts) != 2:
        return False
    
    username, domain = parts
    return len(username) > 0 and '.' in domain

def format_currency(amount, currency='USD'):
    """Format amount as currency string."""
    symbols = {
        'USD': '$',
        'EUR': '€',
        'GBP': '£'
    }
    
    symbol = symbols.get(currency, '$')
    return f"{symbol}{amount:.2f}"

# Example usage demonstrating clear function purposes
def process_order():
    """Process a customer order with proper structure."""
    
    # Sample order data
    items = [
        {'name': 'Laptop', 'price': 999.99, 'quantity': 1},
        {'name': 'Mouse', 'price': 29.99, 'quantity': 2}
    ]
    
    customer_email = "customer@example.com"
    
    # Validate customer
    if not validate_email(customer_email):
        print("Invalid customer email")
        return
    
    # Calculate totals
    total = calculate_total_price(items, tax_rate=0.08, discount=0.1)
    formatted_total = format_currency(total)
    
    print(f"Order total: {formatted_total}")
    print(f"Customer: {customer_email}")

process_order()

Class Organization

# Well-structured class design

class BankAccount:
    """Represents a bank account with basic operations."""
    
    def __init__(self, account_number: str, initial_balance: float = 0.0):
        """Initialize account with number and balance."""
        self.account_number = account_number
        self._balance = initial_balance  # Private attribute
        self._transaction_history = []
    
    @property
    def balance(self) -> float:
        """Get current account balance."""
        return self._balance
    
    def deposit(self, amount: float) -> bool:
        """Deposit money to the account."""
        if amount <= 0:
            return False
        
        self._balance += amount
        self._add_transaction("deposit", amount)
        return True
    
    def withdraw(self, amount: float) -> bool:
        """Withdraw money from the account."""
        if amount <= 0 or amount > self._balance:
            return False
        
        self._balance -= amount
        self._add_transaction("withdrawal", amount)
        return True
    
    def _add_transaction(self, transaction_type: str, amount: float):
        """Private method to record transactions."""
        from datetime import datetime
        
        transaction = {
            'type': transaction_type,
            'amount': amount,
            'timestamp': datetime.now().isoformat(),
            'balance_after': self._balance
        }
        self._transaction_history.append(transaction)
    
    def get_statement(self) -> list:
        """Get list of recent transactions."""
        return self._transaction_history.copy()

# Example of inheritance and composition
class SavingsAccount(BankAccount):
    """Savings account with interest calculation."""
    
    def __init__(self, account_number: str, initial_balance: float = 0.0, 
                 interest_rate: float = 0.02):
        super().__init__(account_number, initial_balance)
        self.interest_rate = interest_rate
    
    def calculate_interest(self) -> float:
        """Calculate interest on current balance."""
        return self._balance * self.interest_rate

# Usage example
account = SavingsAccount("SAV-001", 1000.0, 0.03)
account.deposit(500.0)
account.withdraw(200.0)

print(f"Balance: ${account.balance:.2f}")
print(f"Annual Interest: ${account.calculate_interest():.2f}")
print(f"Transactions: {len(account.get_statement())}")

📋 Code Organization Patterns

PatternPurposeExample
ModulesGroup related functionsmath_utils.py, file_helpers.py
ClassesBundle data and methodsUser, Product, Calculator
PackagesOrganize multiple modulesmodels/, services/, utils/
FunctionsSingle-purpose operationsvalidate_email(), format_date()
ConstantsNamed configuration valuesMAX_RETRIES = 3

🎯 Key Takeaways

🚀 What's Next?

Learn how to write clean, readable code with proper naming conventions and clear logic.

Continue to: Write Clean Code

Was this helpful?

😔Poor
🙁Fair
😊Good
😄Great
🤩Excellent