Challenge your understanding of the SOLID principles of object-oriented design with this engaging quiz. Strengthen your grasp of best practices in software development by answering scenario-based questions focused on single responsibility, open/closed, Liskov substitution, interface segregation, and dependency inversion principles.
Which scenario best demonstrates the Single Responsibility Principle in action?
Explanation: The correct answer is the class focused solely on user authentication, delegating logging to another class, since each class has one responsibility. A class that does payments, invoices, and inventory violates the principle by handling multiple concerns. Similarly, a function that both sorts and formats combines unrelated tasks. The database service managing user and product data mixes responsibilities, making the code harder to maintain.
Which option best illustrates the Open/Closed Principle as applied in a payment system?
Explanation: Extending functionality through subclasses without altering the original code is the essence of the Open/Closed Principle. Modifying the payment class directly increases risk and reduces maintainability. Copying and pasting code leads to duplication and inconsistency, while restricting to a single payment method ignores extensibility altogether.
Which of the following examples violates the Liskov Substitution Principle?
Explanation: The violation occurs when a subclass changes the behavior by rejecting inputs the parent would handle successfully, breaking substitutability. A subclass providing the same functionality upholds the principle. When a child class maintains the contract, there's no violation. Allowing subclasses to replace parents without errors aligns with the principle.
Which design best applies the Interface Segregation Principle to a device interface?
Explanation: Segmenting interfaces allows classes to only implement what they need, respecting the Interface Segregation Principle. A large interface forces unrelated methods onto classes, making maintenance harder. Classes implementing empty methods leads to unnecessary code, and using static utility methods does not effectively use interface-based design.
Which choice best demonstrates the Dependency Inversion Principle in software design?
Explanation: Depending on abstractions enables flexibility and decouples high-level logic from low-level details, as prescribed by the Dependency Inversion Principle. Changing the high-level class or hardcoding module details increases coupling. Directly creating and using concrete classes inside logic functions violates the principle by making the system rigid and harder to adapt.