OOP & SOLID Middle cheat sheet: interview answers
Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.
1. Why is
Square extends Rectanglewith settable width and height a classic LSP violation?function stretch(r: Rectangle) { r.setWidth(5); r.setHeight(4); console.assert(r.area() === 20); }Correct answer: A square must keep its sides equal, so
setHeightalso changes the width and the assertion failsCode written for
Rectangleassumes width and height change independently.Squarecan't keep that promise, so it isn't a behavioral subtype, even though a square "is a" rectangle in geometry.2. According to LSP, how may a subclass change a method's preconditions and postconditions?
Correct answer: Preconditions can only be weakened, postconditions can only be strengthened
A subclass may accept more and promise more, never accept less or promise less. If the parent accepts any amount, a subclass that rejects amounts over 100 breaks callers.
3. Which subclass change breaks LSP?
Correct answer:
withdraw(amount)in the parent accepts any positive amount, the subclass rejects amounts over 1000Strengthening a precondition means some calls that worked with the parent now fail. Adding methods or changing
toString()doesn't break existing callers.4. Which return type is allowed when overriding
Animal create()in Java?Correct answer:
Dog create(), a covariant return typeReturn types may be narrowed (covariance): a caller expecting an
Animalis happy with aDog. Widening the return type would break callers.5. What is the history rule of LSP?
Correct answer: A subtype must not allow state changes that the parent type forbids
If
ImmutablePointis the parent, aMutablePointsubclass breaks code that relied on the point never changing, even if every method signature matches.6. A
ReadOnlyListextendsArrayListand throws fromadd(). What is the cleaner design?Correct answer: Have a read-only interface that the mutable list extends, not the reverse
A mutable list can do everything a read-only list can, plus more, so it's the natural subtype. Kotlin's
ListandMutableListfollow this design.7. What is the difference between a role interface and a header interface?
Correct answer: A role interface covers one client's needs, a header interface mirrors every public method of a class
Extracting
IUserServicewith all 30 methods ofUserServiceis a header interface. ISP prefers role interfaces likeUserFinderthat only list what a client calls.8. With the Dependency Inversion Principle, who should own the
PaymentGatewayinterface?Correct answer: The high-level module that uses it, such as the order domain
The "inversion" is about ownership: the domain defines what it needs, and the infrastructure adapts to it. The source dependency then points from Stripe code to the domain.
9. Which is NOT a form of dependency injection?
Correct answer: Calling
ServiceLocator.get("mailer")inside the methodWith a service locator the class still pulls its dependency itself, and the dependency is hidden from its signature. Constructor, setter and method injection push dependencies in.
10. Why is constructor injection usually preferred over setter injection?
Correct answer: The object is complete right after construction and dependencies can be immutable
With setters, there is a window where the object exists without its dependencies. Setter injection fits optional dependencies with sensible defaults.
11. What is a composition root?
Correct answer: The single place near the app's entry point where the object graph is wired
Business classes only declare dependencies. One place, like
main()or the container setup, creates concrete classes and connects them.12. A constructor takes 9 dependencies. What does this usually mean?
Correct answer: The class has too many responsibilities and should be split
Constructor injection makes the problem visible, which is good. Bundling dependencies into a bag hides the SRP violation instead of fixing it.
13. What does Inversion of Control mean in general?
Correct answer: A framework calls your code, instead of your code calling the library
"Don't call us, we'll call you": a web framework calls your handler, a test runner calls your tests. Dependency injection is one specific form of IoC.
14. Which code follows "Tell, Don't Ask"?
Correct answer:
account.withdraw(amount), where the account checks its own balanceAsking for data and deciding outside spreads the object's rules across callers. Telling the object what to do keeps logic next to the data it uses.
15. What does Command-Query Separation say?
Correct answer: A method should either change state or return data, but not both
Queries are then safe to call any number of times. Exceptions exist, like
stack.pop(), but they should be deliberate. Splitting into separate models is CQRS, a bigger idea.16. Which GRASP principle says to give a responsibility to the class that has the needed data?
Correct answer: Information Expert
The
Orderknows its items, soorder.total()belongs there, not in anOrderCalculatorthat reads every item from outside.17. What is a Pure Fabrication in GRASP?
Correct answer: A class with no domain meaning, made up to keep cohesion high and coupling low
A
UserRepositoryisn't a concept from the business, but putting persistence intoUserwould hurt cohesion. Inventing the repository is a Pure Fabrication.18. Which GRASP principle suggests that
Ordershould createOrderLineobjects?Correct answer: Creator: a class that contains or aggregates B should create B
The order holds its lines and has the data to build them, so
order.addLine(product, qty)is a natural place to create anOrderLine.19. What does Protected Variations in GRASP recommend?
Correct answer: Put a stable interface around the points where change or instability is expected
If the tax rules change every year, hide them behind a
TaxPolicyinterface. It's the same idea behind OCP and information hiding.20. What is the difference between an entity and a value object?
Correct answer: An entity has an identity that persists over time, a value object is defined only by its values
Two customers with the same name are still different people (entities, compared by ID). Two
Money(10, "EUR")objects are interchangeable (values, compared by content).21. Why should value objects usually be immutable?
Correct answer: Shared values can't be changed by one holder behind another's back
If two orders share one
Moneyobject and one of them mutates it, both totals change. With immutable values, sharing is safe and aliasing bugs disappear.22. How should a method that "changes" an immutable
Moneylook?Correct answer:
add(other: Money): Moneythat returns a new objectImmutable objects return new instances:
const total = price.add(tax). The originalpricestays the same, which makes code easier to reason about.23. What goes wrong here in Java?
Set<Point> set = new HashSet<>(); Point p = new Point(1, 2); // mutable, hashCode uses x and y set.add(p); p.setX(10); System.out.println(set.contains(p));Correct answer: It prints
false: the hash changed, so the set looks in the wrong bucketThe object was stored under its old hash. After mutation, lookups compute a new hash and miss it. Fields used in
hashCode()should not change while the object is in a hash collection.24. Why is
equals()withinstanceoftricky when a subclass adds a field?Correct answer: It's hard to keep
equals()symmetric:point.equals(colorPoint)and the reverse can disagreeA
Pointignores color and says "equal", aColorPointchecks color and says "not equal". Common fixes: comparegetClass(), make the classfinal, or use composition.25. What is the fragile base class problem?
Correct answer: A safe-looking change in a parent class breaks subclasses that relied on its internals
If
addAll()in a parent starts callingadd()internally, a subclass that counts calls in both methods suddenly counts twice. Subclasses depend on implementation details.26. What does this code print?
class CountingSet extends Set<number> { added = 0; add(v: number) { this.added++; return super.add(v); } } const s = new CountingSet([1, 2, 3]); console.log(s.added);Correct answer:
0: the overriddenadd()runs, but the field initializer resets the counter aftersuper()The
Setconstructor callsthis.add()for each item, so the override runs three times. But class fields are initialized only aftersuper()returns, soadded = 0overwrites the count. The subclass silently depends on how the parent's constructor works.27. Why is calling an overridable method from a constructor risky?
Correct answer: The subclass override runs before the subclass fields are initialized
In Java, TypeScript and C#, a parent constructor that calls
init()dispatches to the subclass override while the subclass is half-built, so it sees default orundefinedfields.28. How do Template Method and Strategy differ?
Correct answer: Template Method varies steps through subclassing, Strategy through a composed object
Template Method fixes the algorithm in a base class and lets subclasses override hooks. Strategy passes the varying part as an object, so it can change at runtime.
29. What is delegation in OOP?
Correct answer: An object forwards a request to a helper object it holds instead of inheriting the behavior
A
Stackthat holds an array and forwardspushandpopto it exposes only what it needs. Inheriting fromArraywould also exposespliceandsort.30. Why is
class Stack extends Arraya poor design?Correct answer: Callers can use
spliceorunshiftand break the stack's rulesInheritance exposes the whole parent interface. Holding a private array and offering only
push,popandpeekprotects the LIFO invariant.31. What is the Refused Bequest smell?
Correct answer: A subclass uses only a few inherited methods or overrides others to do nothing
If a subclass doesn't want its inheritance, the hierarchy is wrong. Replacing inheritance with delegation is the usual fix.
32. Logic that uses
Orderdata lives inOrderPrinter, which calls six getters ofOrder. Which smell is this?Correct answer: Feature Envy
A method more interested in another class's data than its own probably belongs to that class. Move the calculation into
Orderand let the printer only format.33. Adding one field to a customer requires edits in 12 classes. Which smell is this?
Correct answer: Shotgun Surgery
One change scattered across many classes means a concept isn't kept in one place. Divergent Change is the opposite: one class changes for many unrelated reasons.
34. What is the Middle Man smell?
Correct answer: A class where most methods just forward calls to another class
Some delegation is useful, but a class that only forwards adds a layer with no value. It's the price of overdoing Hide Delegate.
35. What is an anemic domain model?
Correct answer: Domain classes hold only data, while all business logic lives in service classes
Fowler calls it an anti-pattern for rich domains: you pay for objects but write procedural code. For simple CRUD, plain data objects can still be fine.
36. What is a Data Class smell?
Correct answer: A class with only fields and accessors, while other classes do all the work on it
Look at which code uses its data, and move that behavior into the class. DTOs at system boundaries are an exception, they are meant to carry data.
37. What is the Null Object pattern?
Correct answer: An object with neutral behavior used instead of
null, so callers skip null checksA
NullLoggerwhose methods do nothing lets code calllogger.info()withoutif (logger). It works when "do nothing" is a valid default.38. A class has fields
street,city,ziprepeated inCustomer,WarehouseandInvoice. What is the fix?Correct answer: Extract an
Addressvalue object and use it in all three classesData that always travels together is a missing concept (Data Clumps). A value object gives it a name, validation and behavior like
format().39. What is a mixin?
Correct answer: A reusable set of methods added to a class without being its parent in the domain sense
Mixins like
SerializableorEventEmitteradd a capability. In TypeScript they are often functions that take a class and return an extended class.40. What problem do Java default methods in interfaces solve?
Correct answer: Adding a method to an interface without breaking every class that implements it
Java 8 added
List.sort()andIterable.forEach()as default methods. Existing implementations got them for free without code changes.41. A Java class implements two interfaces that both have a default
hello()method. What happens?Correct answer: A compile error until the class overrides
hello()and picks or combines themJava won't guess. The class must override and can call
A.super.hello()orB.super.hello()explicitly.42. What is the diamond problem?
Correct answer: Ambiguity when a class inherits the same member from two parents with a shared ancestor
If
BandCboth overrideA.greet()andDextends both, whichgreet()doesDget? C++ uses virtual inheritance, Python uses the MRO, Java avoids it for classes.43. What does this Python code print?
class A: def who(self): return "A" class B(A): def who(self): return "B" class C(A): def who(self): return "C" class D(B, C): pass print(D().who(), [k.__name__ for k in D.__mro__])Correct answer: B ['D', 'B', 'C', 'A', 'object']
Python's C3 linearization keeps the order of base classes and puts a shared parent after all its children.
Bcomes first, so itswho()wins.44. How does a Python
Protocoldiffer from anABC?Correct answer: A
Protocolis matched by structure, anABCrequires explicit subclassing or registrationAny class with a matching
read()satisfies aReadableprotocol for a type checker, without importing it. AnABCis nominal and can enforce abstract methods at runtime.45. What does
@dataclass(frozen=True)give a Python class?Correct answer: Generated
__init__,__eq__,__repr__, and an error on attribute assignmentFrozen dataclasses are a quick way to write value objects. With
eq=Trueandfrozen=True, Python also generates__hash__, so instances can be dict keys.46. Why might a class have a private constructor and a static
create()method?Correct answer: To validate input, return cached instances or pick a subclass before creating
Named factories like
Money.fromCents(150)andMoney.parse("1.50 EUR")read better than constructor overloads and can return aResultinstead of throwing.47. When does a discriminated union fit better than a class hierarchy?
type Shape = | { kind: "circle"; r: number } | { kind: "rect"; w: number; h: number };Correct answer: When the set of types is fixed but new operations on them are added often
Adding an operation to a union is one new function with an exhaustive
switch. Adding an operation to a class hierarchy means touching every class. This trade-off is the expression problem.48. What does the Liskov Substitution Principle say about exceptions?
Correct answer: A subclass shouldn't throw new kinds of exceptions that callers of the parent don't expect
Callers handle the errors the parent's contract declares. A new unexpected exception from a subclass is like a stronger precondition: working code breaks.
49. What does "program to an interface, not an implementation" mean?
Correct answer: Declare variables and parameters with abstract types so implementations can be swapped
function save(repo: Repository)works with any repository. Concrete classes still exist, they're chosen in one place instead of everywhere.50. Which version better follows OCP for adding new discount types?
Correct answer: A
DiscountRuleinterface with one class per rule, passed to the checkout as a listNew rules are new classes. The checkout iterates over
rulesand callsapply(), and its code doesn't change when marketing invents a new promotion.51. Is it always worth making code open for extension in advance?
Correct answer: No, abstractions for change that never comes add cost, extract them when a real need appears
Guessing variation points leads to Speculative Generality. A common approach is to refactor toward OCP when the second or third variant shows up.
52. Two methods of a payroll system change for different stakeholders:
calculatePayfor accounting andreportHoursfor HR. Both live inEmployee. Why is that a risk?Correct answer: A change for one stakeholder can break behavior that the other relies on
This is Robert Martin's own SRP example: if both methods share a helper and accounting changes it, HR's reports silently change too.
53. What does "depend on abstractions" NOT mean?
Correct answer: That every class, even a simple value like
Money, needs its own interfaceStable, simple classes such as value objects or standard library types can be used directly. Interfaces pay off at boundaries that change or need to be faked.
54. What is the difference between a stub and a mock in tests?
Correct answer: A stub returns prepared data, a mock also checks which calls were made
Stubs support state verification: you check the result. Mocks support behavior verification: you check that
send()was called with the right email.55. Why do tests that mock every collaborator often become fragile?
Correct answer: They lock in how the code works inside, so refactoring breaks them
If a test asserts each internal call, moving logic between classes fails it even when the behavior is correct. Prefer checking outcomes, mock at system boundaries.
56. What is a sealed class or interface in Java and Kotlin?
Correct answer: A type that allows only a fixed, listed set of subtypes
sealed interface Shape permits Circle, Squarelets the compiler check that aswitchcovers every case. It brings union-like exhaustiveness to class hierarchies.57. What is a trait, compared to a mixin?
Correct answer: A reusable set of methods with explicit rules for resolving name conflicts
Traits (Rust, Scala, PHP) are composed, and conflicts must be resolved explicitly instead of depending on the order of inclusion, as with many mixin systems.
58. What does Kotlin's
class Repo(db: Db) : Db by dbdo?Correct answer: Implements the
Dbinterface by forwarding all its methods todbKotlin generates the forwarding methods, so delegation is as short as inheritance. You override only the methods you want to change.
59. A
Reportclass hasgenerate(),formatAsPdf(),formatAsHtml()andsendByEmail(). What is a good first split?Correct answer: Keep data and generation in
Report, move formatting and sending into separate classesFormatting and delivery change for different reasons than report content. Separate
ReportFormatterandReportSenderlet you add CSV or Slack without touching the report.60. What is the benefit of making a class
final(orsealedin C#) by default?Correct answer: Nobody can depend on its internals through inheritance, so it's safer to change
"Design for inheritance or prohibit it": a class not designed for extension can be refactored freely when it's final. Composition stays available for reuse.
61. What is the Law of Demeter often summarized as?
Correct answer: Only talk to your immediate friends, not to strangers
A method may call methods on
this, its parameters, objects it creates and its own fields. Fluent builders and stream chains on one object aren't violations.62. Why isn't
list.stream().filter(x).map(y).toList()a Law of Demeter violation?Correct answer: Each call returns a stream, you don't reach into other objects' structure
The law is about not depending on the internal structure of collaborators. A fluent API on one abstraction doesn't expose any structure.
63. Which is a good reason to introduce an interface with a single implementation?
Correct answer: To invert a dependency at a boundary, such as the database, or to fake it in tests
An interface is worth it when it decouples layers or isolates something slow or external. Interfaces mirroring every class are header interfaces that add noise.
64. What is cohesion measured by, informally?
Correct answer: How much the methods of a class use the same fields and work toward one goal
If methods split into groups that use disjoint fields, the class does two jobs. Metrics like LCOM try to put a number on this.
65. Which type of coupling is considered the worst?
Correct answer: Content coupling: one module changes or relies on the internal data of another
Reaching into another module's private state (via reflection, global variables or direct field access) means any internal change breaks you.
66. What does
Object.freeze(this)at the end of a JavaScript constructor achieve?Correct answer: Shallow immutability: fields can't be reassigned, but nested objects can still change
Object.freezeis shallow. A frozenOrderwith anitemsarray still letsorder.items.push()work unless the array is frozen or copied too.67. What is defensive copying?
Correct answer: Copying mutable inputs and outputs so outside code can't change internal state
A
Periodthat stores theDatepassed to its constructor can be changed later by the caller. Copy on the way in and on the way out, or use immutable types.68. Which statement about abstract classes in TypeScript is true?
Correct answer: They can have constructors, fields and implemented methods next to abstract ones
Abstract classes compile to regular JavaScript classes, so they exist at runtime and support
instanceof. Interfaces, by contrast, are fully erased.69. Why does
instanceofnot work with TypeScript interfaces?Correct answer: Interfaces exist only at compile time and are erased from the JavaScript output
There is nothing to check at runtime. Use a type guard function, a discriminant property or an abstract class if you need a runtime check.
70. How does Python's
super()behave with multiple inheritance?Correct answer: It calls the next class in the MRO, which may not be the direct parent
Cooperative multiple inheritance relies on every class calling
super(). InD(B, C),super()insideBgoes toC, not toA.71. Why is it good practice for a value object to validate itself in the constructor?
Correct answer: An invalid instance can never exist, so code that receives one doesn't recheck it
If
Emailrejects bad strings when created, any function taking anEmailcan trust it. "Parse, don't validate" applies the same idea.72. What is a class invariant?
Correct answer: A condition that must hold for every instance before and after each public method call
"
balance >= 0" or "start <= end" are invariants. Encapsulation exists to protect them: only methods that preserve the invariant can change state.73. A team adds
isAdmin,isGuestandisBannedchecks withifacross 40 places. Which refactoring is usually suggested?Correct answer: Replace the type checks with polymorphism or a role object that encapsulates the rules
Scattered type checks turn every new role into Shotgun Surgery. A
Roleobject with methods likecanEdit()keeps the rules in one place per role.74. What is the Divergent Change smell?
Correct answer: One class is edited for many unrelated reasons, like new formats and new database fields
It's the code-level face of an SRP violation. The fix is to split the class along the lines of the reasons it changes.
75. What does
protectedon a constructor in TypeScript allow?Correct answer: Subclasses can call it through
super(), but outside code can't usenewon the classA protected constructor works like a base class that is not abstract but still shouldn't be created directly. A private constructor goes further and blocks subclasses too.