Skip to content

Concept quiz: architecture, advanced design, and testing

Difficulty: Advanced

Key concepts

  • concept quiz
  • self-check
  • architecture
  • exception safety
  • thread safety
  • ownership
  • testing

This quiz checks the main rules of the architecture, advanced design, and testing sections. Each question names the lesson section it comes from. The questions on ownership, exceptions, and threads are strict: in C++ the difference between a right answer and a nearly right one is often undefined behaviour, so each explanation says exactly why.

How to take it: choose your answer, select “Check answer”, and then read the explanation under every option, not only the one you chose. The wrong options are common mistakes, and each explanation says why it fails. You can change an answer and check it again.

About this quiz.21 questions. Each one links to the lesson it comes from. Fact questions have one answer that follows from the lesson. Judgement questions depend on trade-offs stated in the question; where more than one answer can be defended, the question says so. This is a self-check for your own study, not a test or a certification.

Question 1 of 21FactA request asks to enrol a student in a fourth course, and the rule is at most three courses per student. Where does this check live, and how is the refusal reported?

Choose one answer.

Show the explained answers
  • Right: In the domain, called by the application service; reported as 409, refused
    Right. The check needs stored data (the student’s current courses) and the domain’s rule. The request is fine in itself but refused given what is stored, which is a 409.
  • Not right: At the boundary, reported as 400 with a field problem
    The boundary has only the request. A check’s home is the first place that has everything it needs, and this one needs stored data.
  • Not right: In the application service, reported as 404, not found
    A 404 is for an id that names nothing stored. The student and the courses exist; the enrolment is refused.

Lesson: API contracts and validation placement: classify each check by what it needs

Question 2 of 21FactThe billing relay charges an account in billing’s store (transaction 1), then removes the message from the enrollment outbox (transaction 2). The two stores share no transaction. Transaction 2 fails. What does the lesson’s design leave, and what happens next?

Choose one answer.

Show the explained answers
  • Right: The charge is kept and the message is still first in the outbox; on the next delivery, billing ignores the repeat and the message is removed
    Right. The order is chosen so that any failure leaves the message in the outbox, so it is delivered at least once. Billing’s charge ignores a repeat, so delivering twice charges once.
  • Not right: Both changes are undone together, because the relay runs them as one transaction
    The two stores share no transaction, so there is no moment at which both changes are kept together. That is why the relay needs two.
  • Not right: The student is charged twice when the message is delivered again
    The message is delivered again, but billing ignores a message it has already handled. Without that, this failure would charge twice.
  • Not right: The message is lost, so the charge has no matching record
    The message is removed only after billing has committed, and only by a transaction that succeeds. A failure in either transaction leaves it in the outbox.

Lesson: Transaction and persistence boundaries: the outbox and the relay

Question 3 of 21FactIn the hexagonal version, the store port’s find returns std::optional<domain::Course>, a copy, instead of a pointer into the store. Which of these does the lesson give as reasons or consequences? Choose all that apply.

Choose all that apply.

Show the explained answers
  • Right: A database cannot hand out pointers into its tables
    Right. A port that returned Course* could only be implemented by an adapter that keeps every course in memory, and it would quietly promise that the pointer stays valid.
  • Right: save gives the store a moment at which it knows something changed
    Right. With a pointer, the core would change the stored course directly, and a database adapter would have no moment at which to write it.
  • Right: A use case that forgets to call save loses its change silently, and only a test catches it
    Right. This is one of the costs the lesson lists for handing out copies.
  • Not right: Copies stop two callers from overwriting each other’s changes to the same course
    They do not. Two callers that each find, change, and save the same course can overwrite each other’s change; copies alone do not prevent it.

Lesson: Hexagonal architecture: why the store hands out copies

Question 4 of 21JudgementA small program builds a handful of objects. No adapter is chosen at run time, and the tests build small parts with fakes, never the whole graph. How should the objects be wired?

Choose one answer. This is a judgement question: the answer depends on the trade-offs stated.

Show the explained answers
  • Can be defended: As local variables in main, passed to each other’s constructors
    Defensible, and nothing more is needed. With a handful of objects, no run-time choices, and no need to build the graph anywhere else, main is the composition root.
  • Hard to defend: In an App class that owns the whole graph
    An App class earns its place when tests need the same graph that main builds, adapters are chosen from configuration, the program needs more than one graph, or the declarations need a place of their own. None applies, so it would be a class with one user and nothing to hide.
  • Hard to defend: With a dependency injection container
    C++ rarely needs one: a constructor call is the injection, and the compiler checks every argument. A container is worth considering for graphs built from configuration files or plug-ins, or large graphs with many scoped lifetimes.
  • Hard to defend: With a service locator that each class asks for its collaborators
    That hides the dependencies: a test that forgets to register one fails at run time, not when compiling, and tests in one process share the registry.

Lesson: Dependency injection and composition roots: when main is enough

Question 5 of 21FactWhich of these does the lesson say are expensive to add later, and so worth doing early even if the first version barely needs them? Choose all that apply.

Choose all that apply.

Show the explained answers
  • Right: Keeping rules out of the console
    Right. Moving rules out later means changing everything around them.
  • Right: A stored data format that other people build against
    Right. Anything other people build against, such as a published interface or a stored data format, is expensive to change once they depend on it.
  • Not right: An interface in front of one class
    This is cheap to add when the requirement arrives, so wait for it. An interface without variation, and without a test that needs a substitute, only costs.
  • Not right: A second module split from the first, in code kept free of dependency cycles
    Also cheap to add later, provided the code was kept free of dependency cycles.

Lesson: Choosing an architecture from requirements: justify every added part

Question 6 of 21JudgementAn internal tool is used only by the team that writes it. It stores exactly the settings it shows, and the settings have no rules. How many types should represent a settings record?

Choose one answer. This is a judgement question: the answer depends on the trade-offs stated.

Show the explained answers
  • Can be defended: One struct, read, shown, and saved as it is
    Defensible, and the simplest. The shapes are the same and change together, and data with no rules has no domain object to protect. Split later, at the boundary that starts changing for its own reasons.
  • Hard to defend: Three: a client shape, a domain object, and a stored record, with mappings between them
    The lesson says such a tool gains nothing from three copies of one struct, and the mappings cost code that must be kept in step.
  • Hard to defend: A domain class with private members and getters, plus a separate stored record
    A domain object exists to guard rules. With no rules, private members and getters protect nothing.

Lesson: DTOs, domain objects, and persistence records: when one type is enough

Question 7 of 21FactEach section of a document owns its paragraphs through std::unique_ptr. A comment refers to one paragraph. The paragraph can be deleted while the comment exists, and the comment should find that out the next time it is used. What should the comment hold?

Choose one answer.

Show the explained answers
  • Right: A ParagraphId, looked up in the document when it is used
    Right. An id plus a lookup fits when the target may go first and the source should find out. It keeps the paragraph’s single owner, and it can be saved to a file. Its cost is a lookup each time.
  • Not right: A const Paragraph*
    A raw pointer fits only when the target outlives the source. Here it would dangle silently when the paragraph is deleted, and using it would be undefined behaviour.
  • Not right: A std::weak_ptr<Paragraph>
    It would detect the deletion, but only if every paragraph were owned through std::shared_ptr, which says a paragraph may have many owners when it has one. Use std::weak_ptr when ownership is already genuinely shared.
  • Not right: A std::shared_ptr<Paragraph>
    The comment would keep a deleted paragraph alive and could not tell that it was deleted. A std::shared_ptr owns; a comment does not own its paragraph.

Lesson: Ownership graphs and lifetime design: choosing the kind of reference

Question 8 of 21FactA transfer between two warehouses throws part way through. Afterwards nothing has leaked, and both warehouses are valid objects that keep their invariants, but the source has already lost three items that the destination never received. Which guarantee did the transfer give?

Choose one answer.

Show the explained answers
  • Right: Basic
    Right. No leaks and every invariant holds, but the state has changed. Basic is the minimum for any function.
  • Not right: Strong
    Strong means the observable state is exactly as before the call: all or nothing. Here the source’s stock changed.
  • Not right: None
    With no guarantee, objects may be invalid or leaked. Here both warehouses are valid and nothing leaked.
  • Not right: Nothrow
    Nothrow means the operation never throws. This one did.

Lesson: Exception safety and failure atomicity: the three guarantees

Question 9 of 21FactA transfer works on copies of both warehouses and then puts them in place with two noexcept swaps. In the version that runs on the copies, the audit record is written to an outside store first, before any stock changes. Does the whole operation give the strong guarantee?

Choose one answer.

Show the explained answers
  • Not right: Yes: if anything throws, only the copies have changed
    The audit record is not one of the copies. Copy-and-swap is strong only if its effects are on the copied objects, plus at most one step that cannot be undone, which must come last.
  • Right: No: a failure after the audit is written leaves a record of a transfer that never happened, and no swap removes it
    Right. The audit must be the last step that can throw. The lesson’s version is strong only because it records the audit last.
  • Not right: No, because the swaps can throw
    The class’s swap exchanges the pointers inside the members and allocates nothing, so it is noexcept. Copy-and-swap depends on that.

Lesson: Exception safety and failure atomicity: the strong guarantee by copy-and-swap

Question 10 of 21FactBy the lesson’s rule for noexcept, which of these functions of its Warehouse class should be marked noexcept? Choose all that apply.

Choose all that apply.

Show the explained answers
  • Right: swap, which exchanges the pointers inside the members
    Right. Nothing allocates, so it cannot fail. Leaving noexcept off a swap that cannot throw stops other code from building strong operations on top of it.
  • Right: count, which only reads
    Right. It reads and cannot fail.
  • Not right: The copy constructor
    It allocates, so it can run out of memory. If an exception tries to leave a noexcept function, the program ends, turning an error a caller might handle into an immediate end of the program.
  • Not right: receive, which allocates, checks, and calls the audit store
    It can fail in several ways. The honest promise for an operation that needs memory or another system is basic or strong, not nothrow.

Lesson: Exception safety and failure atomicity: where noexcept belongs

Question 11 of 21Factrecord() adds one to two std::atomic counters, requests and failures, each with fetch_add. In a test every request fails. Another thread loads requests, then failures, while records are made. Which statements are true? Choose all that apply.

Choose all that apply.

Show the explained answers
  • Right: No update is lost, and there is no data race
    Right. Each fetch_add is one indivisible step, and every access is atomic.
  • Right: The reader can see more failures than requests
    Right. It loads the two values at different moments, so it can see a pair that never existed together. In one of the lesson’s runs, 50,605 of a million pairs of reads did.
  • Not right: ThreadSanitizer reports the problem
    It reported nothing. This is a race condition without a data race: every access is safe, and the result is still wrong. TSan does not know the class’s invariants.
  • Right: One mutex that guards both counters, in record() and in a reader that copies both under the same lock, fixes it
    Right. Values that must agree need one mutex, and the reader takes a copy under the lock rather than a reference that escapes it.

Lesson: Thread safety and synchronization: making each number atomic is not enough

Question 12 of 21FactEvery member of RequestStats locks its own mutex, so each call is safe. A caller writes: if stats.snapshot().failures < 100, then stats.record(...). What is true?

Choose one answer.

Show the explained answers
  • Not right: It is safe, because each call is thread safe
    Each call is one step under the lock; two calls in a row are not. This is “check then act”, a very common race condition in code whose every call is thread safe.
  • Right: Another thread can record between the check and the record, so the limit can be passed; the class should offer one member that checks and records under one lock
    Right. A caller’s own lock helps only if every other caller takes the same lock, which the class cannot enforce. So the operation users need in one step belongs in the class’s interface.
  • Not right: It is a data race, which ThreadSanitizer will report
    Every access happens under the mutex, so there is no data race for TSan to find. The bug is in the logic: a race condition.

Lesson: Thread safety and synchronization: a sequence of safe calls is not safe

Question 13 of 21Facttransfer(from, to) locks the mutex of from, then the mutex of to. One thread transfers from account 1 to account 2 while another transfers from 2 to 1, and both hang. Which changes make this deadlock impossible? Choose all that apply.

Choose all that apply.

Show the explained answers
  • Right: Lock both mutexes together with one std::scoped_lock
    Right. Taking every lock at once removes “hold and wait”: no thread holds one lock while it waits for another.
  • Right: Always lock the account with the lower id first
    Right. One fixed order for every thread removes “circular wait”, so no cycle can form.
  • Not right: Make each account’s mutex a std::recursive_mutex
    A recursive mutex lets the thread that already holds it lock it again. Here two different threads each wait for a lock the other holds, so nothing changes.
  • Not right: Add a short sleep between taking the two locks
    A sleep changes only the timing. Each thread can still hold one lock while waiting for the other, so the cycle can still form.

Lesson: Deadlocks and lock ordering: the four conditions

Question 14 of 21Facttransfer tells a listener about each transfer. The listener shows the new balance by calling bank.balance(to), which locks that account’s mutex. Where should transfer call the listener?

Choose one answer.

Show the explained answers
  • Not right: Inside the locked block, so the listener sees the accounts while nothing else can change them
    The listener’s call to balance would try to lock a std::mutex the same thread already holds: undefined behaviour, and a hang in practice. A slow listener would also hold up every transfer on those accounts.
  • Not right: Inside the locked block, after changing the account mutexes to std::recursive_mutex
    That stops the hang but hides the design problem. The listener could see the accounts before the ledger and balances agree, would still hold up other transfers, and its own locks would still add hidden edges to the lock-order graph.
  • Right: After the locks are released, passing a Transfer value built beforehand
    Right. Build the value, do the work under the locks, release them, then call out. The listener also sees the transfer already finished, which is what a notification should report.

Lesson: Deadlocks and lock ordering: never call unknown code while holding a lock

Question 15 of 21FactWhich of these statements about C++ threads are true? Choose all that apply.

Choose all that apply.

Show the explained answers
  • Right: Destroying a std::thread that is still joinable calls std::terminate(), even if its function has already finished
    Right. Its owner must call join() or detach() first. A finished thread that nobody joined is still joinable.
  • Right: The destructor of a std::jthread asks the thread to stop, then joins it
    Right. That is what makes std::jthread a thread that joins itself.
  • Not right: A stop request ends the thread at once, wherever it is
    Cancellation in C++ is cooperative: one side asks, and the running code checks its std::stop_token at points where stopping is safe. A thread killed at an arbitrary instruction could leave a lock held or an object half changed.
  • Not right: An exception that escapes a thread’s function is passed on to the thread that joins it
    The program calls std::terminate(). To carry an exception to another thread, catch it in the thread, or let a std::packaged_task store it in a future, whose get() throws it again.

Lesson: Asynchronous work, cancellation, and shutdown: the tools C++20 gives you

Question 16 of 21FactA thread pool has a std::mutex, a job queue, a condition variable, and a std::vector<std::jthread> of workers that use all three. Where should the workers member be declared?

Choose one answer.

Show the explained answers
  • Right: Last, so that it is destroyed first, while the mutex, the queue, and the condition variable still exist
    Right. Members are destroyed in the reverse of the order they are declared. Normally shutdown() has already joined the workers; the order is the safety net for paths where it has not, such as a constructor that throws after starting some workers.
  • Not right: First, so that the workers start as early as possible
    When the workers start is set by the constructor body, which runs after every member exists, so declaring them first gains nothing. It does change destruction: declared first, the workers are destroyed last, so on a path where shutdown() has not run they would still be running while the mutex, the queue, and the condition variable are destroyed.
  • Not right: Anywhere, because the destructor joins the workers
    A destructor does not run when the constructor throws, so a worker started part way through construction is stopped only by the member’s own destructor. The declaration order decides whether the data still exists then.

Lesson: Asynchronous work, cancellation, and shutdown: the design

Question 17 of 21FactA shop retries a card charge after a timeout, sending an idempotency key with each attempt. How should the key be made?

Choose one answer.

Show the explained answers
  • Right: Derived from the order, such as from its id, so every retry of that payment sends the same key
    Right. The key names the intent, not the attempt. Deriving it from the order lets the shop rebuild it after a restart.
  • Not right: A new random key for each attempt
    Then every attempt looks new to the provider, which is exactly the double charge the key exists to prevent.
  • Not right: A random key made at the first attempt and kept only in memory
    A random key works only if it is saved with the order before the first try. Kept only in memory, a shop that crashes and restarts makes a new one.

Lesson: Idempotency, retries, and duplicate handling: the caller’s half

Question 18 of 21FactThe requirement is “both patients are reminded”, in any order. Which test survives a refactoring that sends the earliest appointment first, which keeps every requirement?

Choose one answer.

Show the explained answers
  • Right: A spy records each message sent, and the test checks which phones were sent to, in any order
    Right. A spy lets the test decide afterwards what to look at, so it checks what was required and nothing more.
  • Not right: A strict, ordered mock expects the two messages in the order they were booked
    When the lesson ran this, the mock test failed against the refactored copy, although every requirement still held. It checked how, not what: an order nobody required.
  • Not right: A stub gives canned answers, and the test checks only that no exception was thrown
    A stub remembers nothing, so this test cannot tell whether anyone was reminded at all.

Lesson: Test doubles, seams, and designing for testability: over-mocking

Question 19 of 21FactA copy of a thread-safe queue reads its waiting counts in stats() without the lock, while other threads write them under the lock. Built without sanitizers, its thread tests passed 100 times out of 100. Which statements are true? Choose all that apply.

Choose all that apply.

Show the explained answers
  • Right: It is a data race, so it is undefined behaviour
    Right. Two threads touch the same memory, at least one writes, and nothing orders the accesses.
  • Right: A ThreadSanitizer build of the same tests reported it
    Right. Built with Clang and TSan, the same tests reported two data races.
  • Not right: One hundred passes show that the code is correct, at least on that machine
    The reads only happened to give sensible numbers. Passing tests sample a few interleavings; they do not prove concurrent code correct.
  • Not right: ThreadSanitizer would also catch a wrong decision made while holding the mutex
    TSan finds data races. A wrong decision with every access under the mutex is a race condition in the logic, and TSan was silent on the lesson’s example of one, correctly.

Lesson: Testing concurrent code and its limits: what ThreadSanitizer finds and misses

Question 20 of 21FactA test of a service sometimes fails with no change to the code. The service reads the system clock directly. What does the lesson’s design do about it?

Choose one answer.

Show the explained answers
  • Right: The service reads the time only through a Clock port, and the tests use a ManualClock
    Right. The lesson calls each cause of flakiness a design decision, not a testing one: the port exists so the tests can control the time.
  • Not right: Failing tests are rerun automatically until they pass
    That is how flaky tests become worse than missing ones: people learn to rerun and ignore them, and then they ignore a real failure.
  • Not right: The test sleeps until it is well clear of any time boundary
    The test would still depend on the real clock, and would be slower. The cause, the service reading the real clock, is still there; the lesson removes the cause instead.

Lesson: Testing strategy: keeping tests deterministic

Question 21 of 21FactA bill is split between people by weights. Nobody can easily state the right parts for every input, but doubling every weight describes the same proportions. Which kind of test checks that doubling the weights gives exactly the same parts?

Choose one answer.

Show the explained answers
  • Right: A metamorphic property
    Right. Change the input in a way whose effect you know, and check that the output changes in that way, or not at all. It needs no knowledge of the right parts, though, like any property, it can itself be wrong.
  • Not right: A table-driven test
    A table lists cases with their expected results, so someone must know the right parts for each row.
  • Not right: A golden master
    A golden master records today’s output to show that nothing changed during a refactoring. It says nothing about how two calls should relate.

Lesson: Property-based and table-driven tests: metamorphic properties