← Back to Home

Code-Alongs

Code-Along 1: Design Patterns Implementation

Key Concepts Covered:

  • Singleton Pattern: Creating a class with only one instance that provides global access
  • Factory Method Pattern: Defining an interface for creating objects and letting subclasses decide which classes to instantiate
  • Observer Pattern: Establishing a one-to-many dependency between objects so that when one object changes state, all dependents are notified

Implementation Example:

// Singleton Pattern Example
public class DatabaseConnection {
    private static DatabaseConnection instance;
    private Connection connection;
    
    private DatabaseConnection() {
        // Private constructor prevents direct instantiation
    }
    
    public static synchronized DatabaseConnection getInstance() {
        if (instance == null) {
            instance = new DatabaseConnection();
        }
        return instance;
    }
    
    public Connection getConnection() {
        if (connection == null) {
            // Initialize connection
        }
        return connection;
    }
}

Code-Along 2: Exception Handling

Key Concepts Covered:

  • Exception Hierarchy: Understanding checked vs. unchecked exceptions in Java
  • Try-Catch Blocks: Properly handling exceptions to prevent application crashes
  • Custom Exceptions: Creating application-specific exception classes
  • Best Practices: Exception handling patterns and when to use them

Implementation Example:

// Custom exception class
public class InsufficientFundsException extends Exception {
    private final double amount;
    
    public InsufficientFundsException(double amount) {
        super("Insufficient funds: attempted to withdraw " + amount);
        this.amount = amount;
    }
    
    public double getAmount() {
        return amount;
    }
}

// Using the custom exception
public class BankAccount {
    private double balance;
    
    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException(amount);
        }
        balance -= amount;
    }
    
    // Client code
    public static void main(String[] args) {
        BankAccount account = new BankAccount();
        try {
            account.withdraw(100.0);
        } catch (InsufficientFundsException e) {
            System.err.println("Transaction failed: " + e.getMessage());
            System.err.println("Attempted amount: " + e.getAmount());
        } finally {
            System.out.println("Transaction completed");
        }
    }
}