Interfaces
Define contracts with interfaces for flexible, maintainable code.
Interfaces define contracts that classes must follow. They specify what methods a class must implement without specifying how they should be implemented. This allows for polymorphism and loose coupling.
What are Interfaces?
Section titled “What are Interfaces?”An interface is a contract that specifies what methods a class must implement. It defines the “what” but not the “how”.
Why Use Interfaces?
Section titled “Why Use Interfaces?”- Polymorphism - Different classes can be used interchangeably
- Loose Coupling - Depend on abstractions, not concrete classes
- Flexibility - Easy to swap implementations
- Testability - Easy to create mock implementations
- Multiple Inheritance - Classes can implement multiple interfaces
Python Interfaces
Section titled “Python Interfaces”Python doesn’t have explicit interfaces like Java, but uses:
- Abstract Base Classes (ABC) - Similar to interfaces
- Protocols - Structural subtyping (duck typing)
- ABC with
@abstractmethod- Enforces method implementation
Multiple Interface Implementation
Section titled “Multiple Interface Implementation”Classes can implement multiple interfaces:
Real-World Example: Notification System
Section titled “Real-World Example: Notification System”Visual Representation
Section titled “Visual Representation”Key Takeaways
Section titled “Key Takeaways”When to Use Interfaces
Section titled “When to Use Interfaces”Use interfaces when:
- You want to define a contract that multiple classes can follow
- You need polymorphism - treat different classes the same way
- You want loose coupling - depend on abstractions
- You need multiple inheritance of behavior (not state)
- You want to make code more testable with mock implementations
Examples:
- Payment processors (different payment methods)
- Notification services (email, SMS, push)
- Data access layers (different databases)
- Storage services (local, cloud, database)
- Authentication providers (OAuth, JWT, etc.)