Concept quiz: architecture, advanced design, and 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.
Your answers are saved only in this browser’s local storage, so you can come back to them. Nothing is sent to a server, and nothing is shared between devices or browsers. “Reset this quiz” below removes them, and so does the reset on the “My progress” page.
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
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
Show the explained answers
- Right: A database cannot hand out pointers into its tables
Right. A port that returnedCourse*could only be implemented by an adapter that keeps every course in memory, and it would quietly promise that the pointer stays valid. - Right:
savegives 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
saveloses 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
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,mainis the composition root. - Hard to defend: In an
Appclass that owns the whole graph
AnAppclass earns its place when tests need the same graph thatmainbuilds, 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
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
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
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 throughstd::shared_ptr, which says a paragraph may have many owners when it has one. Usestd::weak_ptrwhen 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. Astd::shared_ptrowns; a comment does not own its paragraph.
Lesson: Ownership graphs and lifetime design: choosing the kind of reference
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
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’sswapexchanges the pointers inside the members and allocates nothing, so it isnoexcept. Copy-and-swap depends on that.
Lesson: Exception safety and failure atomicity: the strong guarantee by copy-and-swap
Show the explained answers
- Right:
swap, which exchanges the pointers inside the members
Right. Nothing allocates, so it cannot fail. Leavingnoexceptoff 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 anoexceptfunction, 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
Show the explained answers
- Right: No update is lost, and there is no data race
Right. Eachfetch_addis 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
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
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.
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 tobalancewould try to lock astd::mutexthe 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
Transfervalue 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
Show the explained answers
- Right: Destroying a
std::threadthat is still joinable callsstd::terminate(), even if its function has already finished
Right. Its owner must calljoin()ordetach()first. A finished thread that nobody joined is still joinable. - Right: The destructor of a
std::jthreadasks the thread to stop, then joins it
Right. That is what makesstd::jthreada 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 itsstd::stop_tokenat 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 callsstd::terminate(). To carry an exception to another thread, catch it in the thread, or let astd::packaged_taskstore it in a future, whoseget()throws it again.
Lesson: Asynchronous work, cancellation, and shutdown: the tools C++20 gives you
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. Normallyshutdown()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 whereshutdown()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
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
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
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
Show the explained answers
- Right: The service reads the time only through a
Clockport, and the tests use aManualClock
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.
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
Your results
This summary helps you decide what to reread. It is not a certification and does not measure professional skill: a quiz checks that you remember and can apply the lessons’ rules, not that you can design a system.
Reset
Removes your saved answers for this quiz from this browser.