Interview Scenarios: Abstraction in Machine Coding Rounds
Machine coding rounds test your ability to apply abstraction pragmatically within tight time constraints. Here are common scenarios and how to handle them.
Book, Magazine, and DVD implement a LibraryItem interface or extend an abstract LibraryItem class?calculateLateFee() because fees differ. This is IS-A relationship with shared implementation.# title: String
# isCheckedOut: Boolean
+ returnItem(): void
+ calculateLateFee(days): Money
SearchStrategy interface?SearchStrategy interface allows Library class to delegate to TitleSearchStrategy, AuthorSearchStrategy, etc. However, if time is tight and only one search type is requested, implement it directly and mention "this can be abstracted later if we need multiple strategies." Pragmatism over perfection in timed settings.ElevatorScheduler interface with implementations like FCFSScheduler and SCANScheduler. The ElevatorController depends on the interface, not concrete schedulers. This demonstrates understanding of OCP (Open/Closed Principle).Common Interview Questions:
Q: "Why did you use an interface here instead of an abstract class?"
A: Explain the lack of shared state or the need for multiple inheritance. For example: "The Notifiable interface allows both User and Administrator classes to receive notifications without forcing them into a common inheritance hierarchy. Users and Administrators are fundamentally different entities, so interface composition is more appropriate than inheritance."
Q: "How would you add a new payment method without changing existing code?"
A: Demonstrate OCP understanding: "I would create a new class implementing PaymentMethod interface, such as CryptocurrencyPayment. The ParkingTransaction class requires no changes because it depends on the PaymentMethod abstraction, not concrete implementations. I would register the new payment method in the payment factory or dependency injection container."
Q: "Is this abstraction necessary?"
A: Be prepared to justify or simplify. If you created an interface with a single implementation and no clear need for variation, admit it: "You are right, this abstraction is premature. Since we only have one implementation and no anticipated variations, I will refactor to use the concrete class directly." Recognizing over-engineering is a strength, not weakness.