Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 77 ยท CS Fundamentals Interview Questions

OOP, SOLID and Design Patterns Questions

Answer OOP interview questions with confidence: the four pillars, SOLID principles and the singleton, factory, observer and strategy patterns in JavaScript.

Object-oriented design questions are about judgment more than syntax. An interviewer asks "what is polymorphism?" to hear whether you can explain it plainly and show where it helps. They ask about SOLID and patterns to see whether you can keep code easy to change. The examples here use JavaScript classes, but every idea applies to Java, C#, Python and C++.

Background: SOLID principles, Creational and behavioral patterns and Classes in JavaScript.

Four pillars of OOP

Encapsulation Hide state behind methods.
Abstraction Show what, hide how.
Inheritance Reuse and specialize.
Polymorphism One call, many behaviors.
1 / 2

The four pillars

Q: Explain encapsulation, abstraction, inheritance and polymorphism.

  • Encapsulation bundles data with the methods that use it and hides the internals, so outside code cannot put the object into an invalid state.
  • Abstraction exposes a simple interface and hides the complexity behind it. You call account.withdraw(50) without knowing how balances are stored.
  • Inheritance lets a class reuse and specialize another's behavior (an "is-a" relationship).
  • Polymorphism means code can call the same method on different types and each responds in its own way.
JS All four pillars in one small example

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The loop never asks which kind of account it has. That is polymorphism. A good follow-up answer: prefer composition over inheritance when the relationship is "has-a" or when subclasses would override most of the parent, because deep hierarchies are rigid.

SOLID

Q: What does SOLID stand for?

  • S, Single Responsibility: a class should have one reason to change.
  • O, Open/Closed: open for extension, closed for modification. Add behavior by adding code, not by editing tested code.
  • L, Liskov Substitution: a subtype must work anywhere its parent is expected, without surprising callers.
  • I, Interface Segregation: many small, focused interfaces beat one large one.
  • D, Dependency Inversion: high-level code depends on abstractions, and concrete details are passed in (injected).
JS Open/Closed and Dependency Inversion

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because OrderService receives its notifier, a test can pass a fake without sending real messages. That is the practical payoff of the "D".

Q: Give a Liskov violation. The classic one: Square extends Rectangle, where setting the width also changes the height. Code written for rectangles (setWidth(5); setHeight(2) expecting area 10) breaks with a square. The fix is to not use inheritance for that relationship.

Singleton and factory

Q: What is the singleton pattern, and why is it controversial? It guarantees one instance with a global access point. It suits things like a configuration object or a logger. The criticism: it is global state in disguise, so it hides dependencies and makes tests interfere with each other. If you can pass the object in instead, do.

Q: What does a factory do? It centralizes object creation, so callers ask for a kind of thing without naming the concrete class, and adding a new kind touches one place.

JS Singleton and factory

Press Run (or Ctrl + Enter) to see the console output here.

No output.

In JavaScript a plain module that exports one object is often a simpler singleton than a class.

Observer and strategy

Q: Explain the observer pattern. A subject keeps a list of subscribers and notifies them when something happens. The subject does not know what the subscribers do, which decouples the two sides. DOM events, Node's EventEmitter and state stores all work this way. Remember to let subscribers unsubscribe, or you leak memory.

Q: Explain strategy. Put interchangeable algorithms behind the same interface and pick one at runtime. It replaces long if/else or switch chains and satisfies Open/Closed.

JS Observer and strategy

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A function is the lightest possible strategy in JavaScript, which is why this version needs no classes.

How to answer pattern questions

Name the problem first, then the pattern, then a trade-off. "I would use strategy here because pricing rules keep changing and I do not want to edit the checkout function each time. The cost is a few more small units." Avoid forcing a pattern where a plain function will do; interviewers notice over-engineering as much as under-engineering.

Design principles beyond SOLID, and UML

SOLID is the headline, but interviewers also ask about the shorter slogans and about how you communicate a design. Here are the ones to know, with the traps in each.

DRY, KISS and YAGNI

  • DRY (Don't Repeat Yourself): every piece of knowledge should have one authoritative place in the system. The key word is knowledge, not text. Two functions that look the same but change for different reasons are not duplication; merging them couples unrelated things. A practical guide is the rule of three: tolerate a copy once, and extract on the third occurrence, when you can see what really varies.
  • KISS (Keep It Simple): choose the simplest design that meets the requirements. Fewer moving parts means fewer bugs and an easier handover. Simple is not the same as short: a one-line clever expression is not simple if nobody can read it.
  • YAGNI (You Aren't Gonna Need It): do not build features or extension points for needs you only imagine. Speculative generality has a cost now and is usually wrong later. YAGNI does not forbid good structure; it forbids unrequested functionality.

Also expect: composition over inheritance (build behavior by combining small objects instead of deep class trees), the Law of Demeter ("talk only to your immediate friends": order.customer.address.city couples you to three classes' internals), separation of concerns, high cohesion and low coupling, and the principle of least astonishment. These can pull against each other. DRY pushes toward abstraction, YAGNI and KISS push against it, and a good answer says how you decide: by how often the code changes and for which reasons.

JS DRY done badly: merging code that only looks alike

Press Run (or Ctrl + Enter) to see the console output here.

No output.

High-level design versus low-level design

High-level design (HLD) is the system view: services, databases, queues, caches, how they communicate, how the system scales and survives failures. The output is an architecture diagram. Low-level design (LLD) is the code view inside one component: classes, interfaces, methods, relationships and design patterns. The output is a class diagram and code. "Design a URL shortener's services and storage" is HLD (see System Design: The Building Blocks); "design the classes for a parking lot" is LLD (see Low-Level Design).

UML diagrams and the class diagram

UML (Unified Modeling Language) is a standard notation for drawing software. You do not need all fourteen diagram types. The ones worth naming:

Diagram Shows Typical use
Class Classes, attributes, methods, relationships LLD interviews
Sequence Messages between objects over time One use case or API call
Use case Actors and what they can do Requirements
Activity Workflow with branches (like a flowchart) Business process
State machine States and transitions of one object Order status, vending machine
Component / deployment Modules and where they run Architecture

A class diagram box has three parts: the name, the attributes and the methods, with + public, - private, # protected. The part interviewers probe is the relationships, from weakest to strongest coupling:

  • Dependency: one class uses another briefly (a parameter or local variable). Dashed arrow.
  • Association: one class holds a reference to another and knows it. Plain line.
  • Aggregation ("has-a", weak): a whole holds parts that can exist without it. A Team has Players; players survive if the team is deleted. Hollow diamond.
  • Composition ("owns", strong): the parts cannot outlive the whole. An Order owns its OrderLines. Filled diamond.
  • Inheritance ("is-a"): Car extends Vehicle. Hollow triangle arrow.
  • Realization: a class implements an interface. Dashed line with a hollow triangle.
classDiagram
    class Vehicle {
        <<abstract>>
        -String plate
        +start()
    }
    class Car
    class Payable {
        <<interface>>
        +pay(amount)
    }
    class Order {
        +total() int
    }
    class OrderLine
    class Team
    class Player
    Vehicle <|-- Car : inherits
    Payable <|.. Order : realizes
    Order *-- OrderLine : composition
    Team o-- Player : aggregation
    Order ..> Vehicle : dependency

Read *-- as "owns" and o-- as "has". Deleting the Order deletes its lines; deleting the Team leaves the players.

How do you tell aggregation from composition in code? Ask who controls the lifetime. If the part is created inside the whole and dies with it, it is composition; if it is passed in from outside and used elsewhere too, it is aggregation. The stand-in shows the difference.

JS Composition versus aggregation by lifetime

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A good LLD answer starts with the class diagram's nouns (classes), verbs (methods) and relationships, then picks patterns only where they remove a real problem.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which principle says code should be extended by adding new classes instead of editing existing tested code?

    Open/Closed: open for extension, closed for modification.
  2. 2. Why is Square extends Rectangle a classic Liskov Substitution violation?

    A square cannot honor the rectangle contract that width and height change independently.
  3. 3. What is the main downside of the singleton pattern?

    Shared global state makes tests influence each other and hides what code depends on.
  4. 4. In the observer pattern, why should subscribers be able to unsubscribe?

    A forgotten subscription keeps the callback and everything it references alive.
  5. 5. Replacing a long switch over pricing rules with a map of functions is an example of:

    Interchangeable algorithms chosen at runtime behind one call shape is the strategy pattern.

Summary

  • The four pillars: encapsulation, abstraction, inheritance, polymorphism. Prefer composition when "has-a" fits.
  • SOLID: single responsibility, open/closed, Liskov substitution, interface segregation, dependency inversion.
  • Singleton: one shared instance; use sparingly because it is global state.
  • Factory: one place that decides which concrete class to create.
  • Observer decouples a publisher from its subscribers; strategy swaps algorithms behind one interface.
  • Give the problem, the pattern and the trade-off in every answer.
  • DRY is about knowledge, not text; KISS and YAGNI push back against needless abstraction; prefer composition over inheritance.
  • HLD is the system architecture, LLD the classes inside a component; UML class diagrams distinguish dependency, association, aggregation, composition, inheritance and realization.

Next: Security and Cryptography Questions.