Quiz: Clean Classes and SOLID Principles in Java

Total: 5 questions

1. 

What are the SOLID principles?

Five design principles for object-oriented classes collected by Robert C. Martin: Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion. They keep classes small and focused and make it possible to change them without breaking the code that uses them.

2. 

What does the single responsibility principle say?

A class should have only one reason to change: one actor or concern whose requirements drive its changes. It does not mean one method. An Invoice that calculates totals, renders PDF and sends email has three reasons to change and should be split into Invoice, InvoicePdfRenderer and InvoiceMailer.

3. 

Why is List.of() an example of a Liskov substitution problem?

The list returned by List.of() is a List, but its add() throws UnsupportedOperationException, so it promises less than its base type. Code written for any List breaks when it receives this one. The JDK documents add() as an optional operation; in your own hierarchies a subclass that throws from an inherited method signals wrong inheritance.

4. 

What is the Law of Demeter?

A method should talk only to its own fields, its parameters and the objects it creates, not to the internals of objects returned by them. A chain such as customer.getAddress().getCity().getZip() is called a train wreck: it breaks when any class in the chain changes. Ask the object for what you need instead, for example customer.shippingZip().

5. 

What is the difference between dependency inversion and dependency injection?

Dependency inversion is a design principle: high-level and low-level code both depend on abstractions. Dependency injection is a technique for applying it: a class receives its collaborators from outside, usually as interfaces through the constructor, instead of creating them with new. Frameworks such as Spring perform the injection automatically.

Page 1 of 1