Dependency
Temporary use - weakest relationship between classes.
Dependency is the weakest relationship where one class uses another temporarily. The dependent class doesn’t store a reference to the other class - it only uses it as a parameter, local variable, or return type.
What is Dependency?
Section titled “What is Dependency?”Dependency represents:
- “Uses temporarily” relationship
- No ownership - doesn’t store reference
- Temporary use - only during method execution
- Weakest relationship - no coupling beyond method call
Key Characteristics
Section titled “Key Characteristics”- Temporary use - Only during method execution
- No storage - Not stored as instance variable
- Method parameters - Usually passed as parameters
- Dashed arrow in UML diagrams
Basic Dependency Example
Section titled “Basic Dependency Example”class Order: def __init__(self, order_id: str): self.order_id = order_id self.total = 0
def calculate_total(self, calculator): """Dependency - uses Calculator temporarily""" # Calculator is passed in, not stored self.total = calculator.add(100, 50) return self.total
def print_receipt(self, printer): """Dependency - uses Printer temporarily""" printer.print(f"Order {self.order_id}: ${self.total}")
class Calculator: def add(self, a, b): return a + b
class Printer: def print(self, text): print(text)
order = Order("ORD-001")calculator = Calculator()printer = Printer()
order.calculate_total(calculator) # Uses calculatororder.print_receipt(printer) # Uses printer# calculator and printer are not stored in orderpublic class Order { private String orderId; private double total;
public Order(String orderId) { this.orderId = orderId; this.total = 0; }
// Dependency - uses Calculator temporarily public double calculateTotal(Calculator calculator) { // Calculator is passed in, not stored this.total = calculator.add(100, 50); return total; }
// Dependency - uses Printer temporarily public void printReceipt(Printer printer) { printer.print("Order " + orderId + ": $" + total); }}
public class Calculator { public double add(double a, double b) { return a + b; }}
public class Printer { public void print(String text) { System.out.println(text); }}
// Usagepublic class Main { public static void main(String[] args) { Order order = new Order("ORD-001"); Calculator calculator = new Calculator(); Printer printer = new Printer();
order.calculateTotal(calculator); // Uses calculator order.printReceipt(printer); // Uses printer // calculator and printer are not stored in order }}Visual Representation
Section titled “Visual Representation”Real-World Example: Payment Processing
Section titled “Real-World Example: Payment Processing”class ShoppingCart: def __init__(self): self.items = [] self.total = 0.0
def add_item(self, item: str, price: float): self.items.append((item, price)) self.total += price
def checkout(self, payment_processor, validator): """Dependency - uses PaymentProcessor and Validator temporarily""" # Validator is used temporarily if not validator.validate(self.total): return "Invalid amount"
# PaymentProcessor is used temporarily result = payment_processor.process(self.total) return result
class PaymentProcessor: def process(self, amount: float): return f"Processing payment of ${amount:.2f}"
class Validator: def validate(self, amount: float): return amount > 0
cart = ShoppingCart()cart.add_item("Laptop", 999.99)
processor = PaymentProcessor()validator = Validator()
print(cart.checkout(processor, validator)) # Uses both temporarilypublic class ShoppingCart { private java.util.List<String> items; private double total;
public ShoppingCart() { this.items = new java.util.ArrayList<>(); this.total = 0.0; }
public void addItem(String item, double price) { items.add(item); total += price; }
// Dependency - uses PaymentProcessor and Validator temporarily public String checkout(PaymentProcessor processor, Validator validator) { // Validator is used temporarily if (!validator.validate(total)) { return "Invalid amount"; }
// PaymentProcessor is used temporarily return processor.process(total); }}
public class PaymentProcessor { public String process(double amount) { return String.format("Processing payment of $%.2f", amount); }}
public class Validator { public boolean validate(double amount) { return amount > 0; }}
// Usagepublic class Main { public static void main(String[] args) { ShoppingCart cart = new ShoppingCart(); cart.addItem("Laptop", 999.99);
PaymentProcessor processor = new PaymentProcessor(); Validator validator = new Validator();
System.out.println(cart.checkout(processor, validator)); // Uses both temporarily }}Dependency vs Association
Section titled “Dependency vs Association”| Feature | Dependency | Association |
|---|---|---|
| Duration | Temporary | Persistent |
| Storage | Not stored | Stored as reference |
| Lifecycle | No coupling | Some coupling |
| UML Symbol | Dashed arrow | Solid arrow |
| Example | Order uses Calculator | Teacher has Courses |
Key Takeaways
Section titled “Key Takeaways”When to Use Dependency
Section titled “When to Use Dependency”Use Dependency when:
- Class uses another temporarily
- Passing objects as method parameters
- Using objects as local variables
- You want minimal coupling
- Relationship is not persistent
- Objects are created externally
Examples:
- Order uses Calculator (for calculation)
- Order uses Printer (to print receipt)
- ShoppingCart uses PaymentProcessor (to process payment)
- Report uses Formatter (to format output)
- Service uses Logger (to log messages)