Skip to content
Posts

cat ~/posts/engineering-fundamentals-interview-refresh.mdx

2026.10.06

21 min read

โ€“โ€“โ€“ views

ibsanju

Engineering Fundamentals Refresh: OOP, SOLID, ACID, CAP and More

A plain explanation of OOP vs FP, SOLID, ACID, CAP, DRY and KISS, List, Set and Map, design patterns, system design and the STAR method, with examples, differences and trade-offs.

Series ยท Part 1 of 8

Interview Essentials

  1. [01]Engineering Fundamentals Refresh: OOP, SOLID, ACID, CAP and More (you are here)
  2. [02]Mastering Java Interviews: Essential Questions and Answers (Basics)
  3. [03]Design Patterns for Interviews: Singleton, Factory, Builder, Strategy and More
  4. [04]Essential JavaScript Interview Questions and Answers (Basics)
  5. [05]Essential Coding Patterns for Technical Interviews
  6. [06]Essential Coding Patterns for Technical Interviews (Java)
  7. [07]Essential SQL Commands for Developer Interviews
  8. [08]Essential Concepts for Software Testing Quality Engineers (2025)

These topics come up in almost every interview: OOP, SOLID, ACID, CAP, DRY, KISS and STAR. Most developers know the words but find it hard to explain them clearly and give an example.

This post explains each topic in the same four steps:

  1. Why it exists: the problem it solves.
  2. The idea: what it means in simple words.
  3. Example: something small and concrete.
  4. Compare and trade-offs: how it differs from similar ideas, and what it costs.

It is part 1 of the Interview Essentials series and is written for developers with a few years of experience. If a term is unfamiliar, check the glossary first.

Glossary

TermFull formMeaning
OOPObject-Oriented ProgrammingOrganise code as objects that hold data and the code that changes it
FPFunctional ProgrammingBuild programs from functions that do not change anything outside themselves
SOLIDSingle responsibility, Open/closed, Liskov substitution, Interface segregation, Dependency inversionFive rules for writing classes that are easy to change
ACIDAtomicity, Consistency, Isolation, DurabilityWhat a database guarantees for a transaction
BASEBasically Available, Soft state, Eventually consistentA looser alternative to ACID, common in NoSQL databases
CAPConsistency, Availability, Partition toleranceWhen machines cannot talk to each other, you can keep only one of consistency or availability
PACELCPartition: Availability or Consistency; Else: Latency or ConsistencyCAP extended to normal operation, when nothing is broken
DRYDon't Repeat YourselfKeep each piece of knowledge in one place
KISSKeep It Simple, StupidChoose the simplest solution that works
YAGNIYou Aren't Gonna Need ItDo not build something until you need it
GoFGang of FourThe four authors of the classic book on 23 design patterns
STARSituation, Task, Action, ResultA structure for answering behavioural questions
APIApplication Programming InterfaceThe agreed way one piece of software is used by another
SQL / NoSQLStructured Query Language / "Not only SQL"Relational databases with fixed tables / databases with flexible structure
CDNContent Delivery NetworkServers around the world that serve cached copies of your content
Big-OBig-O notationHow the cost of an operation grows as the input size n grows
TransactionA group of database steps that must all succeed or all fail
Network partitionMachines that are running but cannot reach each other

1. OOP vs FP

Why it exists. As a program grows, any part of the code can change any data. When something goes wrong, it is hard to tell which part did it. OOP and FP are two ways to control that.

The idea.

  • OOP groups data and the code that changes it into an object. The object protects its own data, so changes go through its methods.
  • FP uses functions that take input and return output without changing anything else (pure functions), on data that is never modified (immutable data).
OOP keeps data and rules inside an object. FP passes data through a chain of functions.OOP: data and rules togetherBankAccountbalanceprivaterule: no overdraftdeposit()withdraw()Callers use the methods.Nobody edits balance directly.FP: data flows throughcartkeep in-stock itemsapply discounttotalEach step returnsa new value.The original cartis never changed.
Same goal, two shapes: guard the data, or let it flow through.

Example. A bank account is a natural object. It holds a balance and refuses a withdrawal it cannot cover. Calculating a cart total is a natural function: items go in, a number comes out.

// OOP: the data and its rules live together
class BankAccount {
  private double balance;                       // private: only this class changes it
  void withdraw(double amount) {
    if (amount > balance) throw new IllegalStateException("Insufficient funds");
    balance -= amount;
  }
}
 
// FP: input in, result out, nothing is changed
double total = cart.stream()
    .filter(Item::inStock)
    .mapToDouble(Item::price)
    .sum();

OOP is usually explained with four ideas:

  • Encapsulation: keep data private and expose only safe operations. An ATM lets you deposit and withdraw, not open the vault.
  • Abstraction: show what something does, hide how. You use the pedal, not the engine.
  • Inheritance: a type reuses and extends another. An ElectricCar is a Car with a different engine.
  • Polymorphism: one interface, many implementations. pay() works the same way for card, UPI or wallet.

Where you have seen it. Java's ArrayList hides its internal array and only exposes methods such as add and get, which is encapsulation. Java Streams and JavaScript's map, filter and reduce are functional style. A React reducer is a pure function too: it takes the old state and an action and returns the new state.

Compare.

  • State: OOP changes state inside objects. FP creates new values instead.
  • Best for: OOP suits things that live long and have rules (accounts, orders, UI components). FP suits data pipelines (validation, transformations).
  • Testing: pure functions are easiest to test, since the same input always gives the same output.

Trade-offs.

  • OOP strengths: it matches real-world things, and rules stay next to the data. Weaknesses: shared changing state causes bugs, and deep inheritance becomes rigid.
  • FP strengths: predictable, easy to test, safe with concurrency. Weaknesses: unfamiliar at first, and I/O and UI state need extra care.

Common follow-up. What is the difference between abstraction and encapsulation? Abstraction hides complexity behind a simple interface. Encapsulation hides data behind access rules.

2. SOLID

Why it exists. Code that is hard to change breaks in surprising places. A small change in one class ripples into five others. SOLID is five habits that keep changes small and local.

The idea. Each letter is one rule.

S: Single Responsibility. A class should have one reason to change. In a restaurant, the chef cooks and the cashier handles bills. A class that builds a report, saves it to a file and emails it has three reasons to change. Split it into three.

O: Open/Closed. Add new behaviour by adding code, not by editing existing code. If adding a payment method means editing a growing if/else, every change risks breaking the old ones. Instead, each payment method is its own class.

L: Liskov Substitution. A child class must work anywhere its parent is expected. If Penguin extends Bird and Bird has fly(), code that calls fly() on any bird breaks for the penguin. The penguin should not be a child of that parent.

I: Interface Segregation. Prefer several small interfaces over one large one. If a Worker interface has work() and eat(), a robot is forced to implement eat(). Split it into Workable and Eatable.

D: Dependency Inversion. Depend on abstractions, not concrete classes. A lamp works with any socket that follows the standard. It does not care which power plant is behind it. In code, this lets you swap a real service for a fake one in tests.

Where you have seen it. Java's Comparator is Open/Closed: you add a new sort order by writing a new comparator, and List.sort never changes. Spring injects interfaces rather than concrete classes, which is Dependency Inversion. The JDK's own Collections.unmodifiableList implements List but throws on add, which is often cited as a place where Liskov Substitution bends.

The two most often asked in code:

// Open/Closed: a new discount is a new class, existing code is untouched
interface Discount { double apply(double price); }
class FestiveDiscount implements Discount {
  public double apply(double price) { return price * 0.8; }
}
 
// Dependency Inversion: depend on an interface, so a test can pass a fake gateway
interface PaymentGateway { void charge(double amount); }
class CheckoutService {
  private final PaymentGateway gateway;
  CheckoutService(PaymentGateway gateway) { this.gateway = gateway; }
  void pay(double amount) { gateway.charge(amount); }
}

Check yourself

A payment class has a growing switch on payment type. Every new method means editing it. Which principle does that break?

Trade-offs.

  • Benefits: small changes, easier testing, a shared vocabulary in the team.
  • Costs: more classes and indirection. On a small app, applying all five is over-engineering.

Common follow-up. Which principle helps testing most? Dependency Inversion, because you can inject fakes.

3. ACID

Why it exists. Imagine a bank transfer that subtracts 100 from account A, then the server crashes before adding 100 to account B. The money has disappeared. Databases need a way to make a group of steps behave as one.

The idea. A transaction is a group of steps that succeed or fail together. ACID describes what the database guarantees about it.

BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;   -- if anything fails before this, ROLLBACK undoes both updates
  • Atomicity: all steps happen or none do. The transfer never ends half done.
  • Consistency: the rules always hold. A rule like balance >= 0 is never broken.
  • Isolation: transactions running at the same time do not see each other's unfinished work.
  • Durability: once committed, the change survives a crash or power cut.

Try it: a bank transfer

Move 100 from account A to account B. Run it normally, then crash the server halfway. Do it with and without a transaction and compare.

Account A

500

Account B

200

    Total money in the bank: 700

    Where you have seen it. A checkout flow lowers the stock count and creates the order in one transaction. If the second step fails, the first is rolled back, so you never end up with stock removed and no order.

    Isolation in more detail. When transactions overlap, three problems can occur:

    • Dirty read: you read data another transaction has not committed yet, and it may be rolled back. Example: you see a seat as sold, then that payment fails.
    • Non-repeatable read: you read the same row twice and get different values, because someone committed a change in between. Example: a price changes during checkout.
    • Phantom read: you run the same query twice and get different rows. Example: the order count changes in the middle of a report.
    Two timelines of transactions A and B. In the first, A reads a value that B later rolls back. In the second, A reads the same row twice and gets two different values.Dirty read: A reads data that B later rolls backTx ATx BUPDATE price = 120SELECT price -> 120ROLLBACKtimeA used a price (120) that never officially existed.Non-repeatable read: same query, two answersTx ATx BSELECT price -> 100UPDATE price = 120; COMMITSELECT price -> 120timeInside one transaction, A read the same row twice and got 100, then 120.
    Read each lane left to right. Time moves with the arrow.

    Isolation levels decide which of these are allowed. Stricter levels are safer but slower.

    LevelDirty readNon-repeatable readPhantom read
    Read Uncommittedpossiblepossiblepossible
    Read Committedpreventedpossiblepossible
    Repeatable Readpreventedpreventedpossible (by the SQL standard)
    Serializablepreventedpreventedprevented

    PostgreSQL defaults to Read Committed. MySQL (InnoDB) defaults to Repeatable Read.

    Check yourself

    In one transaction you read a row twice and get different values, because another transaction committed a change in between. What is this called?

    Compare: ACID vs BASE. ACID puts correctness first: after a write, everyone sees the new value. BASE puts availability and scale first: after a write, copies catch up shortly after ("eventually consistent"). Payments and inventory need ACID. Feeds, carts and counters can often accept BASE.

    Trade-offs.

    • Benefits: data stays correct under failures and concurrency, and the model is simple.
    • Costs: slower under heavy write load, and harder to spread across many machines.

    Common follow-up. Is the C in ACID the same as the C in CAP? No. In ACID it means the data follows its rules. In CAP it means every read sees the latest write.

    4. DRY, KISS and YAGNI

    Why they exist. Code gets harder to change when the same thing is written in many places, or when it is more complicated than the problem needs. These three habits push the other way.

    The idea.

    • DRY: keep each piece of knowledge in one place. If the tax rate appears in three files, someone will update two and forget the third.
    • KISS: choose the simplest solution that works. Simple code is easier to read, test and fix.
    • YAGNI: do not build features or abstractions for a future that may not come.
    // Not DRY: the tax rule exists in two places and will drift apart
    double invoiceTotal = subtotal + subtotal * 0.13;
    double quoteTotal   = amount + amount * 0.13;
     
    // DRY: one place to change
    static final double TAX_RATE = 0.13;
    static double withTax(double amount) { return amount * (1 + TAX_RATE); }

    Compare. DRY is about knowledge, not about code that looks similar. Two pieces of code that look alike but change for different reasons should stay separate. A common rule is to wait for the third repetition before extracting a shared abstraction. DRY and KISS can also pull in opposite directions: removing every duplicate can make code harder to follow.

    Trade-offs.

    • Benefits: fewer bugs, since each fix happens once, and code that is easier to read and change.
    • Costs: DRY taken too far ties unrelated code together. YAGNI means you may need to refactor later, which is an accepted cost.

    5. CAP theorem and PACELC

    Why it exists. To stay available and fast, systems keep copies of data on several machines. Sooner or later the machines cannot reach each other (a network partition). Then the copies can disagree, and the system has to decide what to do.

    The idea. During a partition you can guarantee only one of:

    • Consistency: every read returns the latest write.
    • Availability: every request gets a response, even if it might be out of date.

    Partition tolerance is not optional in a real distributed system, so the actual choice is CP or AP.

    Example. A bank has two branches and the connection between them is down. A customer asks for their balance.

    • CP: the branch says "please wait until we reconnect". The answer is always right, but sometimes unavailable.
    • AP: the branch answers with what it knows. The system always responds, but the answer may be slightly out of date and is corrected later.

    Try it: two bank branches

    Two branches keep copies of one account. Break the connection, then see what each design choice does.

    When the connection is down, favour

    Branch A

    100

    connected

    Branch B

    100

    Pick a mode, break the connection, then try a deposit and a balance check.

    Where you have seen it. Amazon's Dynamo paper (2007) designed the shopping cart to always accept additions, even during failures, and to merge conflicting versions later. That is AP. Systems built on consensus, such as etcd and ZooKeeper, stop accepting writes when they cannot reach a majority of their nodes. That is CP.

    Compare.

    • CP suits payments, inventory and leader election. Users may see errors or waits during a partition.
    • AP suits feeds, shopping carts and view counters. Conflicts have to be reconciled afterwards.

    Check yourself

    You are building the add to cart feature. During a network partition, which do you favour?

    PACELC adds the normal case. If there is a Partition, choose Availability or Consistency. Else (normal operation), choose Latency or Consistency. Even a healthy system trades speed against freshness, because waiting for all copies to agree takes time.

    Many databases let you choose per operation, for example Cassandra's consistency levels.

    Common follow-up. Can a system be CA? Only on a single machine, or if the network never fails, which is not realistic once data is distributed.

    6. List, Set and Map

    Why they exist. Almost every program stores a collection of things, and the right structure depends on one question: how will I use it?

    The idea.

    • List: items in order, duplicates allowed. Like a playlist. (ArrayList, LinkedList)
    • Set: unique items only. Like a guest list. (HashSet, LinkedHashSet, TreeSet)
    • Map: unique keys, each pointing to a value. Like phone contacts. (HashMap, LinkedHashMap, TreeMap)

    Compare the implementations.

    TypeCostNotes
    ArrayListget O(1), add at end O(1) on average, insert in the middle O(n)Fast reads. Usually the right default list
    LinkedListget O(n), add or remove at the ends O(1)Rarely better than ArrayList in practice
    HashSet, HashMapadd, contains, get O(1) on averageFastest lookups, no order
    LinkedHashSet, LinkedHashMapO(1) on averageKeeps insertion order
    TreeSet, TreeMapO(log n)Always sorted, slower than hash-based

    Quick rules: need index access, use ArrayList. Need to check "have I seen this?", use HashSet. Need counts or lookups by key, use HashMap. Need sorted order, use TreeMap or TreeSet.

    Example. Count word frequency, then find the duplicates.

    List<String> words = List.of("test", "build", "test", "ship", "build", "test");
     
    Map<String, Integer> counts = new HashMap<>();
    for (String w : words) counts.merge(w, 1, Integer::sum);   // {test=3, build=2, ship=1}
     
    Set<String> seen = new HashSet<>();
    Set<String> duplicates = new LinkedHashSet<>();
    for (String w : words) if (!seen.add(w)) duplicates.add(w); // add() returns false if already present
    // duplicates = [test, build]

    Try it: how a HashMap stores keys

    Each key is hashed to pick one of 8 buckets. Java starts with 16 and grows the table as it fills; 8 keeps this small enough to see.

    • bucket 0empty
    • bucket 1empty
    • bucket 2empty
    • bucket 3empty
    • bucket 4empty
    • bucket 5empty
    • bucket 6empty
    • bucket 7empty

    Type a key and add it, or add the sample keys to see collisions.

    Where you have seen it. A LinkedHashMap with removeEldestEntry is the classic way to build an LRU cache, and a HashSet is the quickest way to count unique visitors.

    Common follow-up. How does a HashMap work? Each key is hashed to pick a bucket. Keys that land in the same bucket are stored together (as a list, which Java converts to a balanced tree if it gets large). That is why equals() and hashCode() must agree.

    7. Design patterns

    Why they exist. Developers keep meeting the same design problems. Patterns are named, proven solutions, so a team can say "use a strategy here" and everyone knows what is meant. The book that made them famous was written by the Gang of Four (GoF). You do not need all 23. These five come up most.

    The idea.

    • Singleton: exactly one shared instance, such as a config or a connection pool. Downside: it is global state, so it is harder to test.
    • Factory: create objects without naming the concrete class. You ask a pizza shop for a margherita and the kitchen decides how to make it. Downside: extra classes if there is only one type.
    • Builder: build a complex object step by step, like a custom burger. Useful when there are many optional parts. Downside: more code than a constructor.
    • Strategy: swap an algorithm at runtime. A maps app plans the same trip by car, bike or on foot. Downside: callers must choose.
    • Observer: notify many listeners when something changes, like subscribers to a channel. Downside: chains of updates are hard to trace.

    Where you have seen them. Runtime.getRuntime() is a singleton. Calendar.getInstance() and List.of(...) are factories. StringBuilder and HttpRequest.newBuilder() are builders. The Comparator you pass to list.sort is a strategy. addEventListener in the browser is the observer pattern.

    Strategy is the one to be able to write from memory. It is Open/Closed in action.

    interface SortStrategy { void sort(int[] data); }
    class QuickSort implements SortStrategy { public void sort(int[] d) { /* ... */ } }
    class MergeSort implements SortStrategy { public void sort(int[] d) { /* ... */ } }
     
    class Sorter {
      private SortStrategy strategy;
      Sorter(SortStrategy strategy) { this.strategy = strategy; }
      void sort(int[] data) { strategy.sort(data); }
    }

    Compare.

    • Factory vs Builder: a factory decides which object you get. A builder controls how one complex object is assembled.
    • Strategy vs Observer: with Strategy you pick one behaviour. With Observer, many listeners are told that something happened.

    Trade-offs. Patterns give a shared vocabulary and proven solutions. Overused, they turn simple code into a maze, and they never replace understanding the problem. Eight patterns, with diagrams and demos, are covered in Design Patterns for Interviews.

    8. System design

    Why it exists. Real systems have many parts: users, servers, databases, caches, queues. A system design interview checks whether you can put them together sensibly. There is no single right answer. The interviewer is looking at how you reason.

    A repeatable approach.

    1. Clarify requirements. What must it do (functional)? How fast, how big, how available (non-functional)?
    2. Estimate. Users, requests per second, storage. Rough numbers are enough.
    3. Define the API. The main endpoints, with inputs and outputs.
    4. Model the data. The entities, and SQL or NoSQL with a reason.
    5. Draw the high-level design. Clients, load balancer, services, database, cache, queue.
    6. Go deep on the hard part. Hot keys, scaling reads, consistency.
    7. State the trade-offs. What you chose, what you gave up and why.

    The building blocks.

    • Load balancer: spreads traffic across servers and survives a server failure.
    • Cache (for example Redis): keeps popular data in memory for faster reads and less database load.
    • CDN: serves static content from servers close to the user.
    • Replica: a copy of the database that serves reads and survives failures.
    • Shard: one slice of a large database, so writes and storage scale. Like splitting a phone book into A to M and N to Z.
    • Queue (Kafka, SQS): holds work for later, smoothing spikes and decoupling services.
    • Rate limiter: caps requests per user to protect against abuse and overload.
    System design overview: users reach a CDN and a load balancer, which sends requests to app servers. App servers use a cache, a primary database for writes, replicas for reads, and a queue for slow jobs.UsersCDNimages, CSS, JSLoad balancerspreads requestsApp serverApp serverCachechecked firstPrimaryReplicaQueueemails, slow jobswrites and cache missesreadscopies
    The boxes you will draw in most system design answers.

    Example: a URL shortener.

    • API: POST /shorten takes a long URL and returns a short code. GET /:code redirects to the long URL.
    • Data: a table with code, longUrl and createdAt.
    • Design: generate a unique short code (for example base62 of an ID) and store it. Put a cache in front of reads, because redirects are far more frequent than creations.
    • Trade-off: reads vastly outnumber writes, so optimise the read path. A short delay before a new link is visible everywhere is acceptable, which leans toward availability (AP).

    Trade-offs you will be asked about.

    • SQL vs NoSQL: SQL gives relations, joins and transactions with a fixed schema. NoSQL gives a flexible schema and easier horizontal scaling, with weaker joins.
    • Vertical vs horizontal scaling: vertical means a bigger machine, which is simple but has a ceiling and a single point of failure. Horizontal means more machines, which scales further but adds complexity.
    • Caching: reads become fast and cheap, but data can be stale and invalidation is hard to get right.

    9. STAR method

    Why it exists. "Tell me about a time when..." questions invite rambling. STAR gives the answer a shape.

    The idea.

    • Situation: the context, briefly.
    • Task: what you were responsible for.
    • Action: what you did, specifically. Spend most of your time here.
    • Result: the outcome, with numbers if you can, and what you learned.

    Example. "Tell me about a time you improved a process."

    Situation: Our end-to-end test suite failed on roughly one run in three, so the team had stopped trusting it.

    Task: I was asked to make it reliable before the next release.

    Action: I grouped the failures by cause, replaced fixed sleeps with explicit waits, isolated test data per run, and added retries only for known network-dependent steps.

    Result: Flaky failures dropped sharply, the team used the suite as a release gate again, and I documented the patterns for new tests.

    Tips. Say "I" for what you did, not only "we". Give a measurable result. Prepare four or five stories in advance (a challenge, a failure, a conflict, leadership, a big win) and reuse them across questions.

    Sources and further reading

    • Martin Kleppmann, Designing Data-Intensive Applications (2017): chapters on transactions, isolation levels and consistency.
    • DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store" (SOSP, 2007): the shopping cart example.
    • Gilbert and Lynch, "Brewer's Conjecture and the Feasibility of Consistent, Available, Partition-Tolerant Web Services" (2002): the proof of CAP.
    • Haerder and Reuter, "Principles of Transaction-Oriented Database Recovery" (1983): where the name ACID comes from.
    • Gamma, Helm, Johnson and Vlissides, Design Patterns: Elements of Reusable Object-Oriented Software (1994).
    • Robert C. Martin, Clean Architecture (2017): the SOLID principles.
    • PostgreSQL documentation, "Transaction Isolation": what each isolation level really does in PostgreSQL.

    This is part 1 of the Interview Essentials series. A good next step is Java Interview Questions and Answers.

    Enjoyed this? Leave a reaction

    Share this article

    Comments

    Loading commentsโ€ฆ

    Leave a comment

    Enjoying this post?

    Don't miss out. Get an email whenever I post, no spam.

    Subscribe Now