OOP & SOLID Senior 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. Liskov and Wing define subtyping behaviorally. What does that add beyond matching method signatures?
Correct answer: Subtypes must keep the parent's invariants, contracts and allowed state changes
A type checker only sees signatures. Behavioral subtyping is about meaning: anything provable about the parent's objects must stay true for the subtype's objects.
2. Why are Java arrays covariant a design flaw?
Object[] items = new String[2]; items[0] = 42;Correct answer: It compiles, but throws
ArrayStoreExceptionat runtimeArrays are both read and written, so they should be invariant. Java made them covariant and added a runtime check. Generic collections like
List<String>are invariant instead.3. What does PECS mean for Java generics?
Correct answer: Producer
extends, Consumersuper: read from? extends T, write to? super TCollections.copy(List<? super T> dest, List<? extends T> src)readsTfrom the source and writesTinto the destination. That's covariance for reading and contravariance for writing.4. Why must method parameter types be contravariant for a safe override?
Correct answer: Callers pass arguments valid for the parent, so the override must accept at least those
If
feed(food: Food)is overridden asfeed(food: Meat), a caller holding the parent type can passGrassand break the subclass. Accepting a wider type is always safe.5. Why does TypeScript accept this override even with
strictFunctionTypeson?class Animal {} class Dog extends Animal { bark() {} } class Handler { handle(a: Animal) {} } class DogHandler extends Handler { handle(d: Dog) { d.bark(); } }Correct answer: Method parameters stay bivariant,
strictFunctionTypeschecks only function-typed propertiesFor compatibility with patterns like DOM event handlers, methods declared with method syntax are checked bivariantly. Declaring
handle: (a: Animal) => voidas a property would make the override a compile error.6. What is the expression problem?
Correct answer: Adding both new types and new operations without changing existing code is hard
Class hierarchies make new types cheap and new operations expensive. Unions with functions make operations cheap and types expensive. Visitors, type classes and multimethods try to get both.
7. How does the Visitor pattern shift the expression problem trade-off?
Correct answer: New operations become new visitor classes, but adding a node type changes every visitor
A visitor turns a class hierarchy into something like a union: good for compilers with a stable AST and many passes, bad when node types change often.
8. What problem does double dispatch solve?
Correct answer: Choosing behavior based on the runtime types of two objects, not just the receiver
shape.intersects(other)depends on both shapes. Single-dispatch languages emulate it with a second virtual call, as Visitor does. Languages like Julia or CLOS have multiple dispatch built in.9. Which overload runs in Java, and why?
void collide(Shape a, Shape b) { System.out.println("shape"); } void collide(Circle a, Circle b) { System.out.println("circle"); } Shape x = new Circle(); Shape y = new Circle(); collide(x, y);Correct answer: "shape": overloads are picked at compile time from the declared types
Overloading is static dispatch. Only the receiver of a virtual call is dispatched dynamically, which is exactly why double dispatch or pattern matching is needed here.
10. How do Java 21 pattern matching and sealed types change the Visitor trade-off?
Correct answer: An exhaustive
switchover a sealed hierarchy replaces many visitors with checked functionsWith
sealed interface Expr permits Num, Add, aswitchwith record patterns is checked for completeness. Adding a subtype makes every non-exhaustive switch fail to compile, like a visitor but with less code.11. What does a virtual method table (vtable) do?
Correct answer: Maps each virtual method of a class to its implementation, for fast dynamic dispatch
Each object points to its class's vtable, so a virtual call is an indirect jump. JITs often remove it via inlining when a call site sees only one type (monomorphic).
12. Why can megamorphic call sites be slower in JIT-compiled languages like Java or JavaScript?
Correct answer: With many receiver types, the JIT can't inline one target and falls back to a slow lookup
V8 and HotSpot use inline caches that work best with one or a few shapes. It rarely matters for design, but explains why hot loops over very mixed types can be slow.
13. What is the yo-yo problem?
Correct answer: Understanding a call requires jumping up and down a deep inheritance hierarchy
When
this.foo()in a base class may be overridden on any of six levels, the reader has to trace the whole chain. Shallow hierarchies and composition avoid this.14. Why is "open recursion" (
thiscalls dispatched to subclasses) the root of the fragile base class problem?Correct answer: Self-calls inside the parent become hidden extension points that subclasses rely on
If the parent's
addAll()callsthis.add(), that internal detail is part of the de facto contract. Changing it breaks subclasses even though no public signature changed.15. What is the Parallel Inheritance Hierarchies smell?
Correct answer: Each new subclass in one hierarchy forces a matching subclass in another
CarandCarRenderer,TruckandTruckRenderer: every new vehicle needs two classes. Merging the hierarchies or moving the varying part into composition usually helps.16. What is a DDD aggregate?
Correct answer: A cluster of objects treated as one unit for changes, with a root that guards its invariants
An
Orderwith itsOrderLines is an aggregate: outside code goes throughorder.addLine(), so the rule "total under the credit limit" is checked in one place.17. Why do DDD guidelines recommend referencing other aggregates by ID rather than by object?
Correct answer: It keeps aggregates small and independently loadable, with clear transaction boundaries
If
Orderholds a fullCustomer, loading or saving one drags in the other and invites changes to both in one transaction.customerIdkeeps the boundary explicit.18. What is a common rule about transactions and aggregates?
Correct answer: Change one aggregate per transaction, and sync others through domain events
Aggregates are consistency boundaries. Rules across aggregates are usually eventually consistent:
OrderPlacedtriggers the inventory reservation separately.19. How should
equals()andhashCode()work for a JPA entity with a database-generated ID?Correct answer: Carefully: the ID is null before saving, so ID-based hashing breaks sets of new entities
A new entity put in a
HashSetand then persisted changes its hash. Common fixes are a business key, a client-generated UUID, or a constanthashCodewith ID-basedequals.20. Why can ORM lazy-loading proxies surprise OOP code?
Correct answer: The object is a generated subclass, so
getClass()checks and direct field access misbehaveHibernate returns a runtime subclass.
equals()usinggetClass()fails against a proxy, and reading fields directly instead of through getters can see uninitialized values.21. What is the object-relational impedance mismatch?
Correct answer: Objects use identity, references and inheritance, while tables use keys, joins and rows
Inheritance has no direct relational form, object graphs don't map cleanly to joins, and identity means different things. ORMs hide some of this but can't remove it.
22. What does the Stable Dependencies Principle say?
Correct answer: Depend in the direction of stability: volatile packages should depend on stable ones
A package many others depend on is hard to change. If it depends on something that changes often, it inherits that churn. This is DIP applied at package level.
23. What does the Stable Abstractions Principle add to that?
Correct answer: Stable packages should be abstract, so they can be extended without being changed
A stable package full of concrete code is rigid. If it's mostly interfaces, it can stay stable while implementations elsewhere change.
24. What does the Common Closure Principle say?
Correct answer: Classes that change together for the same reasons belong in the same package
It's SRP for packages: a change should touch one package, not five. The Common Reuse Principle pulls the other way, so packages balance between the two.
25. What is connascence?
Correct answer: A measure of coupling: two parts are connascent if changing one requires changing the other
Connascence of name (renaming a method) is weak. Connascence of position (argument order) or meaning (magic values) is stronger. The guideline: weaken it as distance grows.
26.
createUser("Ann", "ann@x.io", true, false, 3)has which kind of strong connascence?Correct answer: Connascence of position and meaning: callers must know the order and what each value means
Swap two booleans and the code still compiles. Named parameters, an options object or value types like
Roleturn this into weaker connascence of name.27. What is a captive dependency in a DI container?
Correct answer: A long-lived service holds a shorter-lived one, so the short one outlives its scope
A singleton that receives a per-request
DbContextkeeps the first request's context forever. Containers like ASP.NET Core can validate scopes to catch this.28. Why is a Service Locator considered worse than constructor injection by many authors?
Correct answer: Dependencies hide in method bodies, so the API lies about what a class needs
You only find out that
OrderServiceneeds a mailer when a test crashes. Constructor injection makes the dependency part of the class's visible contract.29. What is temporal coupling in a class API?
Correct answer: Methods must be called in a specific order, but the API doesn't enforce it
If
connect()must precedesend(), the object has an invalid intermediate state. Constructors that produce ready objects, or types likeConnectionreturned byconnect(), remove it.30. How does hexagonal architecture (ports and adapters) apply DIP?
Correct answer: The domain defines ports as interfaces, and adapters for DB, HTTP or queues implement them
Dependencies point inward: Postgres and REST code depend on the domain, not the reverse. The domain can be tested with in-memory adapters.
31. What is a seam, in the sense of working with legacy code?
Correct answer: A place where behavior can change without editing the code there, like an injected dependency
Introducing seams like an interface or a constructor parameter lets you put legacy code under test before refactoring it.
32. What is the Humble Object pattern?
Correct answer: Move logic out of hard-to-test UI or I/O code into a testable object, leaving a thin shell
A view that only renders what a presenter computed is humble. The presenter has all the logic and can be unit-tested without a browser or device.
33. Why are immutable objects safe to share between threads without locks in Java?
Correct answer: With
finalfields and nothisescape, the memory model shows other threads the built stateFinal field semantics give safe publication: after the constructor finishes, other threads see the final values. No later writes means no data races.
34. What breaks the safety of
finalfields in an immutable Java class?Correct answer: Letting
thisescape from the constructor, like registering a listenerIf another thread gets the reference before the constructor finishes, it may see default values. The final field guarantee only covers objects published after construction.
35. Why do persistent data structures make immutability practical for large collections?
Correct answer: A modified version shares most of its structure with the old one instead of copying it all
Adding to a persistent vector creates a few new tree nodes and reuses the rest. Immer, Clojure and Scala collections use this to keep updates close to O(log n).
36. Alan Kay, who coined "object-oriented", stressed which idea most?
Correct answer: Messaging between objects, more than classes and inheritance
Kay described objects as little computers that communicate by messages and hide their state. Erlang processes and actors are close to that view.
37. "Objects are a poor man's closures, closures are a poor man's objects." What does it mean?
Correct answer: Both bundle behavior with hidden state, so each can emulate the other
A function returning
{ increment, get }over a privatecountis an object. An object with onecall()method is a closure. The choice is about ergonomics.38. How do TypeScript branded types help when structural typing is too permissive?
type UserId = string & { readonly __brand: "UserId" }; type OrderId = string & { readonly __brand: "OrderId" };Correct answer: They emulate nominal types, so a
UserIdcan't be passed where anOrderIdis expectedTwo plain
stringIDs are interchangeable, which invites swapped arguments. A brand exists only in the type system and costs nothing at runtime.39. What does type erasure in Java generics mean for OOP design?
Correct answer:
List<String>andList<Integer>share one runtime class, so you can't overload on themvoid f(List<String>)andvoid f(List<Integer>)clash after erasure. You also can't writenew T()orinstanceof List<String>.40. Which critique of SOLID is most fair?
Correct answer: Applied mechanically, it yields tiny interfaces and indirection with no real benefit
Each principle answers a cost of change. Without that cost, the abstractions are overhead. Robert Martin himself frames SOLID as being about managing dependencies.
41. How do the SOLID principles map to functional programming?
Correct answer: They still apply: passed-in functions give DIP and OCP, small modules give SRP and ISP
Passing a
fetchUserfunction instead of importing the HTTP client is dependency inversion. Higher-order functions extend behavior without modifying code.42. Why is Information Expert sometimes in tension with SRP?
Correct answer: The class with the data may attract unrelated behavior, like persistence or formatting
Orderhas the data to save itself to SQL or render HTML, but those are different reasons to change. Pure Fabrications like repositories resolve the tension.43. When is an anemic model with transaction scripts a reasonable choice?
Correct answer: For simple CRUD with little domain logic, where rich objects would add ceremony
Rich domain models pay off when rules are complex and change often. A thin admin panel over a database often doesn't need them.
44. How does Tell, Don't Ask relate to read-heavy screens and CQRS?
Correct answer: Commands go through rich objects, while reads can use simple query models with getters
Behavior that changes state belongs in the domain. Displaying a report doesn't, so a separate read model or DTOs avoid bloating aggregates with presentation getters.
45. What does the Liskov principle imply for a cache decorator around a repository?
Correct answer: It must keep the repository's contract, including when callers see their own writes
If callers expect read-after-write, a cache that serves the old value breaks them. Decorators are substitutes, so they inherit every behavioral promise.
46. Why is "is-a" in the real world a poor test for using inheritance?
Correct answer: Subtyping is about substitutable behavior, which real-world categories don't promise
A square is a rectangle and a penguin is a bird, yet both models break LSP. Ask "can it be used everywhere the parent is?" instead.
47. What risk comes with a shared
commonorcorelibrary used by every service?Correct answer: It becomes a stable dependency that is hard to change and couples all teams
Shared domain classes across services create distributed coupling. Small, stable utility libraries are fine, shared business models usually aren't.
48. Why can the same concept, like
Customer, have different models in different bounded contexts?Correct answer: Each context needs different data and rules, and one shared model would serve none of them well
Billing cares about payment terms, shipping about addresses, marketing about preferences. A single
Customerclass for all of them becomes a God object.49. What is a domain event in OOP terms?
Correct answer: An immutable object describing something that happened, raised by an aggregate
OrderPlaced { orderId, total, at }lets other parts react without theOrderknowing about them. It decouples aggregates and supports eventual consistency.50. Which approach best replaces a deep
Employeehierarchy where roles change at runtime?Correct answer: Give
Employeearolefield holding a strategy object that can be swappedObjects can't change class, but they can change collaborators. Composition with a role object (State or Strategy) models promotions without recreating the employee.
51. How can you break up a God class safely in a production system?
Correct answer: Cover it with tests, then extract cohesive groups of methods and fields into new classes step by step
Characterization tests pin current behavior. Extract Class along clusters of fields that change together, delegating from the old class until callers migrate.
52. What is the Strangler Fig approach in the context of OO refactoring?
Correct answer: Route calls through a facade and replace the old implementation piece by piece behind it
The facade lets old and new code live side by side. Each behavior moves to the new model when ready, and the old code shrinks until it can be removed.
53. Why are getters on value objects less of a problem than on entities?
Correct answer: Values are immutable, so exposing their data can't break invariants
Reading
money.amountcan't put the object into a bad state. The real risk is outside code duplicating logic that belongs to the value, like currency conversion.54. What is wrong with this "immutable" class?
final class Team { private final List<String> members; Team(List<String> members) { this.members = members; } List<String> members() { return members; } }Correct answer: The list is shared with the caller, so the team can change from outside
finalonly prevents reassigning the field. UseList.copyOf(members)in the constructor, which also makes the getter's return value unmodifiable.55. Interface Segregation at a service boundary often leads to what?
Correct answer: Client-specific APIs, such as a backend for each frontend, instead of one API for all
A mobile app and an admin panel need different shapes of data. BFFs or GraphQL let each client depend only on what it uses.
56. How do OCP and sealed, exhaustive hierarchies relate?
Correct answer: They trade off: sealed types close the set of types to make operations safe to add
OCP via polymorphism keeps types open. Sealed types keep the operation side open with compiler-checked switches. Choose based on which axis changes more.
57. What is the main design risk of reflection-based frameworks that set private fields?
Correct answer: They bypass constructors and invariants, so objects can exist in states the class forbids
Deserializers and ORMs that skip constructors can create an
Emailwith an invalid value. Validating in factories used by the framework, or on load, restores the guarantees.58. What does encapsulation have to do with team boundaries (Conway's law)?
Correct answer: Stable interfaces between modules let teams change internals without coordinating
Information hiding was originally framed by Parnas as a way to divide work. A module's interface is a contract between the people who build and use it.
59. Why do React hooks illustrate "composition over inheritance"?
Correct answer: Reusable stateful logic is composed from functions instead of inherited from base classes
Before hooks, sharing logic meant mixins or HOCs. A
useAuth()hook is a small composable unit, which is the same idea as composing objects.60. What does Python's
__init_subclass__or a metaclass let a base class do, and what's the risk?Correct answer: Hook into every subclass definition, at the cost of hidden, surprising behavior
Plugin registries use it to auto-register subclasses. It's powerful but implicit: defining a class now has side effects that readers may not expect.
61. What is the risk of a deep hierarchy of abstract base classes in a framework?
Correct answer: Users must understand many layers to extend it, and every layer becomes a frozen public API
Each protected method is an extension point users may rely on. That's why many frameworks moved from inheritance to interfaces, hooks and composition.
62. How does DIP enable a plugin architecture?
Correct answer: The core defines an interface, plugins implement it, and the core never imports plugins
VS Code, ESLint and webpack load plugins through interfaces the core owns. New plugins ship without changing or rebuilding the core.
63. Why can a
ResultorEithertype be better than exceptions for domain errors in OO code?Correct answer: The possible failures become part of the method's type, so callers can't ignore them
withdraw(): Result<Balance, InsufficientFunds>makes failure explicit in the contract. Unchecked exceptions hide it, which matters for LSP too.64. What does "make illegal states unrepresentable" mean for class design?
Correct answer: Shape the types so invalid combinations of fields can't be built at all
Instead of
isLoading,dataanderrorfields that can conflict, use a union or a sealed type:Loading | Loaded(data) | Failed(error).65. What is an Identity Map?
Correct answer: A cache that ensures each database row is loaded as one object per session
Without it, loading the same customer twice gives two objects that can diverge. ORMs keep an identity map inside the unit of work.
66. Why might you prefer an abstract class over an interface for a public library API?
Correct answer: You can add methods with default behavior later without breaking implementers
Adding a method to an interface used to break every implementer. Default methods narrowed this gap in Java and C#, but abstract classes can also hold state and protected helpers.
67. What is the main idea of "functional core, imperative shell"?
Correct answer: Keep decisions in pure functions or immutable objects, and push I/O to a thin outer layer
The core is easy to test without mocks. The shell gathers inputs, calls the core and performs side effects. It's Humble Object applied to the whole app.
68. Why can overusing interfaces with one implementation hurt navigation and design?
Correct answer: Every call jumps to an interface, and the indirection hides where the logic is
"Go to definition" lands on an interface with nothing in it. Add the abstraction when there's a second implementation, a boundary or a test need.
69. In a dynamically typed language, how is LSP usually enforced?
Correct answer: By contracts in docs and by shared tests that every implementation must pass
A contract test suite run against every implementation of a
Storageprotocol checks behavior, which is what LSP is about anyway.70. Why is mutable shared state the main enemy of both concurrency and local reasoning?
Correct answer: Any holder can change it at any time, so no single piece of code knows its current value
Aliased mutation causes data races across threads and "spooky action" within one thread. Encapsulation limits who can mutate, immutability removes mutation.
71. What does the Acyclic Dependencies Principle require, and how is a cycle usually broken?
Correct answer: No cycles between packages, break them by introducing an interface owned by one side
If
billingimportsordersandordersimportsbilling, they can't be built or released separately. DIP inverts one edge to make the graph acyclic.72. What is a key difference between C++ and Java in how methods dispatch by default?
Correct answer: C++ methods are non-virtual unless marked
virtual, Java instance methods are virtual by defaultIn C++, calling a non-virtual method through a base pointer runs the base version even if the subclass redefines it. Java needs
final,staticorprivateto avoid virtual dispatch.73. A team wants to share behavior between
InvoiceandQuoteby extending aDocumentbase class. What question decides whether that's right?Correct answer: Will they always change together and be used interchangeably by the same code?
Similar-looking code that changes for different reasons is accidental duplication. Merging it into a base class couples two concepts that will drift apart.
74. Why is a mutable global singleton especially harmful for testability?
Correct answer: Tests share its hidden state, so their results depend on the order they run in
One test changes the config singleton, the next one fails mysteriously. Passing the dependency in (or using a container scope per test) keeps tests isolated.
75. What does Martin Fowler's Aliasing Bug describe?
Correct answer: Two references to one mutable object, where a change through one surprises the other
Passing a mutable
Dateto two objects and then changing it alters both. Value objects should be immutable to make this class of bug impossible.