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. 1. Why is Square extends Rectangle with 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 setHeight also changes the width and the assertion fails

    Code written for Rectangle assumes width and height change independently. Square can't keep that promise, so it isn't a behavioral subtype, even though a square "is a" rectangle in geometry.

  2. 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. 3. Which subclass change breaks LSP?

    Correct answer: withdraw(amount) in the parent accepts any positive amount, the subclass rejects amounts over 1000

    Strengthening a precondition means some calls that worked with the parent now fail. Adding methods or changing toString() doesn't break existing callers.

  4. 4. Which return type is allowed when overriding Animal create() in Java?

    Correct answer: Dog create(), a covariant return type

    Return types may be narrowed (covariance): a caller expecting an Animal is happy with a Dog. Widening the return type would break callers.

  5. 5. What is the history rule of LSP?

    Correct answer: A subtype must not allow state changes that the parent type forbids

    If ImmutablePoint is the parent, a MutablePoint subclass breaks code that relied on the point never changing, even if every method signature matches.

  6. 6. A ReadOnlyList extends ArrayList and throws from add(). 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 List and MutableList follow this design.

  7. 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 IUserService with all 30 methods of UserService is a header interface. ISP prefers role interfaces like UserFinder that only list what a client calls.

  8. 8. With the Dependency Inversion Principle, who should own the PaymentGateway interface?

    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. 9. Which is NOT a form of dependency injection?

    Correct answer: Calling ServiceLocator.get("mailer") inside the method

    With 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. 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. 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. 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. 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. 14. Which code follows "Tell, Don't Ask"?

    Correct answer: account.withdraw(amount), where the account checks its own balance

    Asking 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. 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. 16. Which GRASP principle says to give a responsibility to the class that has the needed data?

    Correct answer: Information Expert

    The Order knows its items, so order.total() belongs there, not in an OrderCalculator that reads every item from outside.

  17. 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 UserRepository isn't a concept from the business, but putting persistence into User would hurt cohesion. Inventing the repository is a Pure Fabrication.

  18. 18. Which GRASP principle suggests that Order should create OrderLine objects?

    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 an OrderLine.

  19. 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 TaxPolicy interface. It's the same idea behind OCP and information hiding.

  20. 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. 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 Money object and one of them mutates it, both totals change. With immutable values, sharing is safe and aliasing bugs disappear.

  22. 22. How should a method that "changes" an immutable Money look?

    Correct answer: add(other: Money): Money that returns a new object

    Immutable objects return new instances: const total = price.add(tax). The original price stays the same, which makes code easier to reason about.

  23. 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 bucket

    The 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. 24. Why is equals() with instanceof tricky when a subclass adds a field?

    Correct answer: It's hard to keep equals() symmetric: point.equals(colorPoint) and the reverse can disagree

    A Point ignores color and says "equal", a ColorPoint checks color and says "not equal". Common fixes: compare getClass(), make the class final, or use composition.

  25. 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 calling add() internally, a subclass that counts calls in both methods suddenly counts twice. Subclasses depend on implementation details.

  26. 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 overridden add() runs, but the field initializer resets the counter after super()

    The Set constructor calls this.add() for each item, so the override runs three times. But class fields are initialized only after super() returns, so added = 0 overwrites the count. The subclass silently depends on how the parent's constructor works.

  27. 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 or undefined fields.

  28. 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. 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 Stack that holds an array and forwards push and pop to it exposes only what it needs. Inheriting from Array would also expose splice and sort.

  30. 30. Why is class Stack extends Array a poor design?

    Correct answer: Callers can use splice or unshift and break the stack's rules

    Inheritance exposes the whole parent interface. Holding a private array and offering only push, pop and peek protects the LIFO invariant.

  31. 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. 32. Logic that uses Order data lives in OrderPrinter, which calls six getters of Order. 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 Order and let the printer only format.

  33. 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. 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. 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. 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. 37. What is the Null Object pattern?

    Correct answer: An object with neutral behavior used instead of null, so callers skip null checks

    A NullLogger whose methods do nothing lets code call logger.info() without if (logger). It works when "do nothing" is a valid default.

  38. 38. A class has fields street, city, zip repeated in Customer, Warehouse and Invoice. What is the fix?

    Correct answer: Extract an Address value object and use it in all three classes

    Data that always travels together is a missing concept (Data Clumps). A value object gives it a name, validation and behavior like format().

  39. 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 Serializable or EventEmitter add a capability. In TypeScript they are often functions that take a class and return an extended class.

  40. 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() and Iterable.forEach() as default methods. Existing implementations got them for free without code changes.

  41. 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 them

    Java won't guess. The class must override and can call A.super.hello() or B.super.hello() explicitly.

  42. 42. What is the diamond problem?

    Correct answer: Ambiguity when a class inherits the same member from two parents with a shared ancestor

    If B and C both override A.greet() and D extends both, which greet() does D get? C++ uses virtual inheritance, Python uses the MRO, Java avoids it for classes.

  43. 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. B comes first, so its who() wins.

  44. 44. How does a Python Protocol differ from an ABC?

    Correct answer: A Protocol is matched by structure, an ABC requires explicit subclassing or registration

    Any class with a matching read() satisfies a Readable protocol for a type checker, without importing it. An ABC is nominal and can enforce abstract methods at runtime.

  45. 45. What does @dataclass(frozen=True) give a Python class?

    Correct answer: Generated __init__, __eq__, __repr__, and an error on attribute assignment

    Frozen dataclasses are a quick way to write value objects. With eq=True and frozen=True, Python also generates __hash__, so instances can be dict keys.

  46. 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) and Money.parse("1.50 EUR") read better than constructor overloads and can return a Result instead of throwing.

  47. 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. 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. 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. 50. Which version better follows OCP for adding new discount types?

    Correct answer: A DiscountRule interface with one class per rule, passed to the checkout as a list

    New rules are new classes. The checkout iterates over rules and calls apply(), and its code doesn't change when marketing invents a new promotion.

  51. 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. 52. Two methods of a payroll system change for different stakeholders: calculatePay for accounting and reportHours for HR. Both live in Employee. 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. 53. What does "depend on abstractions" NOT mean?

    Correct answer: That every class, even a simple value like Money, needs its own interface

    Stable, 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. 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. 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. 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, Square lets the compiler check that a switch covers every case. It brings union-like exhaustiveness to class hierarchies.

  57. 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. 58. What does Kotlin's class Repo(db: Db) : Db by db do?

    Correct answer: Implements the Db interface by forwarding all its methods to db

    Kotlin generates the forwarding methods, so delegation is as short as inheritance. You override only the methods you want to change.

  59. 59. A Report class has generate(), formatAsPdf(), formatAsHtml() and sendByEmail(). What is a good first split?

    Correct answer: Keep data and generation in Report, move formatting and sending into separate classes

    Formatting and delivery change for different reasons than report content. Separate ReportFormatter and ReportSender let you add CSV or Slack without touching the report.

  60. 60. What is the benefit of making a class final (or sealed in 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. 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. 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. 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. 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. 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. 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.freeze is shallow. A frozen Order with an items array still lets order.items.push() work unless the array is frozen or copied too.

  67. 67. What is defensive copying?

    Correct answer: Copying mutable inputs and outputs so outside code can't change internal state

    A Period that stores the Date passed 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. 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. 69. Why does instanceof not 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. 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(). In D(B, C), super() inside B goes to C, not to A.

  71. 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 Email rejects bad strings when created, any function taking an Email can trust it. "Parse, don't validate" applies the same idea.

  72. 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. 73. A team adds isAdmin, isGuest and isBanned checks with if across 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 Role object with methods like canEdit() keeps the rules in one place per role.

  74. 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. 75. What does protected on a constructor in TypeScript allow?

    Correct answer: Subclasses can call it through super(), but outside code can't use new on the class

    A 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.