Interface Examples in CS Thinking

Start with the recap, study the fully worked examples, then use the practice problems to check your understanding of Interface.

This page combines explanation, solved examples, and follow-up practice so you can move from recognition to confident problem-solving in CS Thinking.

Concept Recap

A software interface is the visible contract that tells other parts of a program how to interact with a module, function, or system. It defines the inputs, outputs, and rules of use without exposing the internal implementation.

An interface is like a menu: it tells you what you can ask for without showing the kitchen.

Read the full concept explanation โ†’

How to Use These Examples

  • Read the first worked example with the solution open so the structure is clear.
  • Try the practice problems before revealing each solution.
  • Use the related concepts and background knowledge badges if you feel stuck.

What to Focus On

Core idea: Good interfaces make modules easy to use, test, replace, and understand.

Common stuck point: An interface describes what a module does and how to use it, not how it is implemented internally.

Sense of Study hint: When defining an interface, write down the inputs, outputs, possible errors, and any rules the caller must follow. Keep that contract stable even if the internal code changes.

Worked Examples

Example 1

easy
A module exposes only `getPrice(itemId) -> cents`. Internally it caches results. If we replace the cache with a database lookup but `getPrice` still returns the same value for the same id, do callers need to change?

Answer

No\text{No}

First step

1
List the contract: input `itemId`, output `cents`, behavior `same id -> same cents`.

See the full worked solution + why-it-works coaching

SetupKey insightWhy it worksCommon pitfallConnection

Unlock answer keys One Family plan โ€” every worked solution, all subjects

Example 2

medium
A function's docs say 'idempotent: calling twice has the same effect as calling once.' A team rewrites it so a second call doubles the effect. Is this a breaking change even though the signature didn't change?

Example 3

medium
Two queues, `RingBufferQueue` and `LinkedListQueue`, both implement `Queue` with `enqueue(x)`, `dequeue() -> x`. A caller depends only on `Queue`. What design pattern lets the caller swap implementations?

Example 4

medium
You want to test a function `placeOrder(cart)` that internally calls `paymentGateway`. You don't want real charges in tests. Which property of `paymentGateway`'s interface enables a test double?

Example 5

hard
A class `Stack<T>` exposes `push`, `pop`, and `getInternalArray()`. Why does the third method undermine the interface?

Example 6

hard
A `Cache.get(key)` interface promises 'either the cached value or a fresh fetch.' But callers cannot tell which. Why might exposing a `wasHit` boolean still be a bad interface change?

Example 7

challenge
A graphics library promises `draw(shape)` runs in O(1)O(1) time. Internally a maintainer makes it O(n)O(n) where nn is total scene size. The output is identical. Did this break the interface?

Practice Problems

Try these problems on your own first, then open the solution to compare your method.

Example 1

easy
An interface specifies inputs, outputs, and rules of use. What does it deliberately HIDE?

Example 2

easy
A function is declared as `area(width, height) -> number`. What are its inputs?

Example 3

easy
For `area(width, height) -> number`, what is the output type?

Example 4

easy
Which of these is part of a function's interface? A) the loop it uses internally B) the names and types of its parameters

Example 5

easy
A module documents that `sqrt(x)` requires xโ‰ฅ0x \ge 0. What part of the interface is this requirement?

Example 6

easy
Why does a stable interface let you replace a module's internal code freely?

Example 7

easy
A REST endpoint promises to return JSON with a field `total`. A caller relies on `total`. What do we call this promise?

Example 8

easy
A team renames a public function's parameter and changes its order without telling callers. What is the likely result?

Example 9

medium
Function contract: `divide(a, b) -> number`, constraint `b != 0`. A caller passes `b = 0`. Whose responsibility was the violated constraint, and what should the interface have done if it must accept any b?

Example 10

medium
Two implementations of `sort(list) -> list` exist: one bubble sort, one merge sort. A caller works with both unchanged. What does this demonstrate about the interface?

Example 11

medium
A library function `getUser(id)` used to return `null` for a missing user. A new version throws an error instead. Existing callers checked for `null`. What kind of change is this?

Example 12

medium
A class exposes a public field `count` that other modules read and write directly. Later you want to validate writes. Why is the exposed field a design problem?

Example 13

medium
A function's documented contract: input a non-empty list, output its maximum. A caller passes an empty list. Is the bug in the caller or the function?

Example 14

medium
You design a payment module. Which is the BETTER interface decision? A) expose `chargeCard(token, cents)` and hide the HTTP calls B) expose the raw HTTP client and let callers build requests

Example 15

medium
An API returns `{ ok: true, data: [...] }` on success and `{ ok: false, error: "..." }` on failure. Why is including the `ok` flag good interface design?

Example 16

medium
Module A calls `formatDate(d)`. The author changes it internally from a loop to a library call, output identical. Do A's tests need to change?

Example 17

medium
A function `getConfig() -> Map` returns a map. A caller does `getConfig().get("timeout")` and gets nothing back for a missing key. To make the contract clear, what should the interface specify about absent keys?

Example 18

challenge
You must add a new optional behavior to a widely-used function `parse(text)` without breaking any existing caller. Which approach preserves the contract: A) add a required new parameter, B) add an optional parameter with a default, C) change the return type? Justify.

Example 19

challenge
A function's contract is `f(x) -> y` with the rule 'never throws; returns a sentinel on bad input'. Internally it sometimes throws. Is the contract satisfied, and what is the precise problem?

Example 20

challenge
You publish `area(shape)`. Two callers exist. Caller 1 passes only rectangles; Caller 2 passes circles. To keep ONE interface that serves both without callers knowing the internal shape logic, what design principle should the interface rely on?

Example 21

easy
Which of these is part of a function's PUBLIC interface? A) which local variables it uses, B) the parameter names and return type it documents.

Example 22

easy
A function `roundUp(x) -> int` requires `x >= 0`. What kind of interface element is the rule `x >= 0`?

Example 23

easy
True or False: changing the BODY of a function but keeping its signature and documented behavior is a breaking change.

Example 24

easy
Which is a STRONGER interface guarantee: 'returns a list' or 'returns a sorted list of unique ids'?

Example 25

medium
A library publishes `sendEmail(to, subject, body)`. Version 2 reorders parameters to `sendEmail(subject, body, to)`. Which property of the interface broke?

Example 26

medium
You want callers to be UNABLE to depend on a helper. Where should the helper live?

Example 27

medium
`calcTax(amount, region)` was added a new required `currency` parameter. Existing callers don't pass it and stop compiling. Which interface principle was violated?

Example 28

medium
An interface documents that `withdraw(amount)` throws `InsufficientFunds` when balance is too low. The implementation silently returns 0 instead. Is the interface satisfied?

Example 29

medium
An interface declares `parse(json) -> Document`, no return-type variants. The implementation returns `null` on malformed input. Where is the bug?

Example 30

medium
An interface returns timestamps as 'a number' without saying seconds vs milliseconds. What kind of interface defect is this?

Example 31

medium
A team marks all helper methods `public` 'in case someone needs them later.' How does this hurt the interface?

Example 32

hard
A contract states: 'returns results in arbitrary order.' A new implementation always returns sorted results. Some callers begin to depend on sorting. The maintainer later reverts. What went wrong?

Example 33

hard
Two interfaces, narrow `Reader { read(n) -> bytes }` and wide `File { read, write, seek, lock, stat }`. A code that only consumes data should depend on which, and why?

Example 34

hard
A method declares it can throw `IOException`. A subclass override declares it can throw `IOException` or `SQLException`. Why does this violate Liskov substitution?

Example 35

hard
An API uses URL `/v1/users` and you want to change the response shape incompatibly. What is the standard interface technique?

Example 36

hard
A method `delete(id)` returns `void` on success and on missing-id alike. What hidden cost does this 'forgiving' interface impose on callers?

Example 37

challenge
Design problem: you must expose ONE function that lets callers schedule, cancel, and query work items. Why is a single `doStuff(action, payload)` worse than three separate functions, in interface terms?

Example 38

challenge
You publish `Comparator<T>` with one method `compare(a, b) -> int`. A caller's class compares unstably (returns different signs across calls). Whose contract was broken โ€” the interface's or the caller's?

Background Knowledge

These ideas may be useful before you work through the harder examples.

modular design