Why does bad code, which seems quick to write, end up being slower?
Reveal answer
Because over time it becomes impossible to maintain: every change gets more expensive and the team's productivity plummets.
Source: Notes, ch. 1 — Clean Code
Jan. 24, 2026, 5:02 p.m.
Prentice Hall
One of the most influential works in software development, this book contains a series of patterns and best practices for writing code. The ideal line length, how to structure a function, or what a code comment should convey — the author has a strong opinion on each of these points and many more. With plenty of examples and written in a very clear style, it is a useful tool for learning to improve the quality and, above all, the readability of the code we write.
Progress saved only in this browser · log in to save it to your account
Uncheck to exclude.
No questions match these filters.
Why does bad code, which seems quick to write, end up being slower?
Because over time it becomes impossible to maintain: every change gets more expensive and the team's productivity plummets.
Source: Notes, ch. 1 — Clean Code
What does LeBlanc's Law say?
"Later equals never": cleanup put off until later almost never happens.
Source: Notes, ch. 1 — Clean Code
The manager pushes to deliver faster by sacrificing quality. What does the author say the developer should do?
Defend good code: the developer is the one who knows its importance, and bad code is slower in the long run — giving in to the pressure delays the deadline itself.
Source: Notes, ch. 1 — Clean Code
Why is readability so central to clean code?
Because we read code far more than we write it; making it easier to read also speeds up writing.
Source: Notes, ch. 1 — Clean Code
What is the Boy Scout Rule?
Leave the code cleaner than you found it, with small incremental improvements on each pass.
Source: Notes, ch. 1 — Clean Code
You are going to fix a bug in a function and notice a variable called d. What does the Boy Scout Rule suggest?
Take the chance to rename it with a name that reveals intent (e.g. daysSinceCreation) — a small, incremental improvement.
Source: Notes, ch. 1 — Clean Code
The book presents a single, agreed-upon definition of clean code.
False: there are many definitions (elegant, efficient, clear, simple, tested…) and several schools of thought; the book is one of them.
Source: Notes, ch. 1 — Clean Code
What should a good name communicate?
Intent: the what, how and why of that variable, to the point of making comments unnecessary.
Source: Notes, ch. 2 — Meaningful Names
Improve: int d; // elapsed time in days.
Use a name that makes the comment unnecessary, such as int elapsedTimeInDays.
Source: Notes, ch. 2 — Meaningful Names
Why avoid calling something that is not a list accountList?
Because the name disinforms: it suggests a type that is not true; better to avoid the type in the name (e.g. accounts).
Source: Notes, ch. 2 — Meaningful Names
Using l and O as variable names is problematic because they are confused with 1 and 0.
True: it is a classic example of a disinformative name.
Source: Notes, ch. 2 — Meaningful Names
What is the problem with names such as a1/a2 or ProductInfo/ProductData?
They differ only in spelling, without any difference in meaning; the reader does not know which to use. Distinctions between names must be meaningful.
Source: Notes, ch. 2 — Meaningful Names
Why use pronounceable names, like customer instead of cstmr?
Because programming is a social activity: pronounceable names can be discussed and remembered easily.
Source: Notes, ch. 2 — Meaningful Names
When are single-letter names (such as i, j) acceptable?
Only in very short local scopes; otherwise use searchable names, longer if necessary — the length of a name should match the size of its scope.
Source: Notes, ch. 2 — Meaningful Names
Which name is easiest to find with a search in a large project?
A long, descriptive name is unique in a search; magic numbers and single letters show up everywhere.
Source: Notes, ch. 2 — Meaningful Names
Which encodings in names does the author say to avoid?
Hungarian notation (type in the name), member prefixes (m_) and the I for interfaces.
Source: Notes, ch. 2 — Meaningful Names
What is the grammatical rule for class and method names?
E.g. Customer, Account for classes; postPayment, deletePage for methods.
Source: Notes, ch. 2 — Meaningful Names
Why are names like Manager, Processor or Info bad signs in a class?
Because they are vague: they don't say what the class does and usually indicate a class with too many responsibilities.
Source: Notes, ch. 2 — Meaningful Names
What does "one word per concept" mean?
Always using the same term for the same idea — not mixing get, fetch and retrieve for equivalent operations.
Source: Notes, ch. 2 — Meaningful Names
There are add methods that sum values and you want to create one that inserts an item into a collection. Should you call it add?
No: there would be different semantics under the same name (a pun). Use another name, such as insert or append.
Source: Notes, ch. 2 — Meaningful Names
Which domain should names come from: the solution or the problem?
Prefer technical terms from the solution domain (e.g. JobQueue, Visitor), which programmers understand; when there are none, use terms from the problem domain (e.g. Customer).
Source: Notes, ch. 2 — Meaningful Names
When should you add context to a name, like addrFirstName?
When the context is not evident; ideally a class (e.g. Address) provides the context and makes the prefix unnecessary.
Source: Notes, ch. 2 — Meaningful Names
The author recommends humorous names to make code memorable.
False: don't be "cute" or funny; be clear and direct.
Source: Notes, ch. 2 — Meaningful Names
What is the ideal size of a function for the author?
Very small: 20 lines is already a lot; the ideal is a few lines, with at most one or two levels of indentation.
Source: Notes, ch. 3 — Functions
What is the fundamental rule about what a function should do?
Do one thing only, do it well, and do only that.
Source: Notes, ch. 3 — Functions
What does keeping one level of abstraction per function mean?
Not mixing high-level operations (e.g. getHtml()) with low-level details (e.g. .append("\n")) in the same function.
Source: Notes, ch. 3 — Functions
A function generateReport() calls fetchData(), format() and, in between, does manual string index manipulation. What is wrong?
It mixes levels of abstraction: the string manipulation should go into its own function, leaving generateReport at the high level only.
Source: Notes, ch. 3 — Functions
What should be done with switch statements, according to ch. 3?
Hide them in an abstract factory: the switch appears only once and creates polymorphic objects; the rest of the code uses polymorphism, via inheritance.
Source: Notes, ch. 3 — Functions
Is it bad to have long function names?
No: a long, descriptive name is better than a short, cryptic one; choosing well may take several attempts.
Source: Notes, ch. 3 — Functions
What is the ideal number of arguments for a function?
Zero (niladic) is ideal, then one (monadic) and two (dyadic); three is the limit and should be avoided; more than that, no.
Source: Notes, ch. 3 — Functions
Why do many arguments make testing harder?
Because they multiply the input combinations that need to be covered.
Source: Notes, ch. 3 — Functions
Why are boolean (flag) arguments a terrible idea?
Because they declare that the function does more than one thing — one for true, another for false; better to split it into two functions.
Source: Notes, ch. 3 — Functions
Conceptually refactor render(page, isSuite).
Split it into two functions with clear names, such as renderForSuite(page) and renderForSingleTest(page).
Source: Notes, ch. 3 — Functions
What should you do when a function needs three or more related arguments?
Group them into their own object (e.g. Point instead of x, y) and pass that object.
Source: Notes, ch. 3 — Functions
What are the acceptable forms of monadic function?
Asking a question about the argument, transforming it and returning the result, or treating it as an event — making it clear when it is an event.
Source: Notes, ch. 3 — Functions
Why should functions not have side effects?
Because they do something hidden beyond what the name promises, creating obfuscation and temporal coupling between actions.
Source: Notes, ch. 3 — Functions
checkPassword(user, pass) validates the password and, if correct, initializes the session. What is the problem and the solution?
A hidden side effect that creates temporal coupling (it can only be called when it is safe to start the session). Separate the actions or give it a name that says so, such as checkPasswordAndInitializeSession.
Source: Notes, ch. 3 — Functions
Why avoid output arguments (modifying the argument in place)?
They are counterintuitive; if a function needs to change state, let it be that of the object that owns the method (self/this).
Source: Notes, ch. 3 — Functions
What does the command-query separation principle say?
A function should either do something (command) or answer something (query), never both.
Source: Notes, ch. 3 — Functions
Why is if (set("username", "unclebob")) confusing, and how do you fix it?
You can't tell whether it asks if the attribute already had that value or whether it set it successfully. Separate them: if (attributeExists("username")) { setAttribute("username", "unclebob"); }.
Source: Notes, ch. 3 — Functions
Why prefer exceptions to error codes?
Error codes violate command-query separation and create dependencies (the caller must handle the error right away); exceptions separate the normal flow from the handling.
Source: Notes, ch. 3 — Functions
How should a function with try/except be structured?
The try block should call a function of its own; handling errors is already "one thing", so the function should contain nothing beyond the try/except/finally.
Source: Notes, ch. 3 — Functions
Why is avoiding duplication so important?
Because each duplicate is one more place to rewrite and forget during a change; it is analogous to database normalization.
Source: Notes, ch. 3 — Functions
The author requires a single return and no break/continue in every function, without exception.
False: since functions are small, breaking these rules every now and then is acceptable — except GOTO.
Source: Notes, ch. 3 — Functions
How does the author say one arrives at functions like these?
Through iterative refinement: nobody writes like this the first time; you write, test and keep refactoring.
Source: Notes, ch. 3 — Functions
Why does the author say comments are a necessary evil?
Because they make up for the code's failure to express itself; moreover, they fall out of sync with the code.
Source: Notes, ch. 4 — Comments
Improve: // check whether the employee is eligible for full benefits followed by if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)).
Replace the comment with a function with an explanatory name: if (employee.isEligibleForFullBenefits()).
Source: Notes, ch. 4 — Comments
A bad comment is better than no comment.
False: bad comments are worse than none — they disinform and clutter.
Source: Notes, ch. 4 — Comments
Which of these is considered a good comment?
Explaining intent is good; authorship and commented-out code are already kept by Git, and redundancy only clutters.
Source: Notes, ch. 4 — Comments
Name types of acceptable comments.
Legal (copyright), informative (e.g. explaining a regex), intent, clarification of values we don't control, warnings of consequences, TODOs and amplification.
Source: Notes, ch. 4 — Comments
Are TODO comments acceptable without restriction?
No: they serve for future tasks, but they don't justify leaving bad code in the system.
Source: Notes, ch. 4 — Comments
Why not leave commented-out code?
Others are afraid to delete it and it piles up; Git already keeps the old code.
Source: Notes, ch. 4 — Comments
Why have change-log and attribution comments become bad?
Because version control (Git) already records who changed what and when.
Source: Notes, ch. 4 — Comments
What does the author think of requiring a docstring on every function?
It is a terrible idea: it clutters the code; in non-public code, this formality only gets in the way.
Source: Notes, ch. 4 — Comments
What is a comment with nonlocal information?
A comment that talks about other parts of the system; it should explain only the adjacent code, otherwise it goes stale without anyone noticing.
Source: Notes, ch. 4 — Comments
What do closing brace comments (} // end while) indicate?
That the function is too long; it is better to shorten it so that ifs and whiles are easy to follow.
Source: Notes, ch. 4 — Comments
What is the goal of code formatting?
Communication: showing care and making the code readable, with consistent rules — not rigidity for its own sake.
Source: Notes, ch. 5 — Formatting
What is the newspaper metaphor for formatting?
The file should read top to bottom like a news story: headline and overview at the top, details increasing downward; short files, like articles.
Source: Notes, ch. 5 — Formatting
What file size do the notes suggest as good?
Somewhere between 200 and 500 lines, although it depends; smaller files are easier to understand.
Source: Notes, ch. 5 — Formatting
What is conceptual affinity in vertical formatting?
Related concepts should be vertically close, in the same file, so the reader doesn't have to jump between sections.
Source: Notes, ch. 5 — Formatting
How should a function that calls another be positioned?
Close together, with the caller above the callee, from high level to low level — the code reads top to bottom.
Source: Notes, ch. 5 — Formatting
Where should local and instance variables be declared?
Local ones as close as possible to their use (loop variables with the loop); instance ones at the top of the class, in a standard place.
Source: Notes, ch. 5 — Formatting
What line width does ch. 5 consider excessive?
More than 120 characters; common limits are 80, 100 or 120.
Source: Notes, ch. 5 — Formatting
Why does the author advise against aligning declarations in columns?
The alignment draws attention to the wrong column; if a list is long enough to call for alignment, the problem is the length of the list.
Source: Notes, ch. 5 — Formatting
For short ifs and loops, it is acceptable to collapse the indentation onto one line.
False: it is tempting, but indentation should be kept to make the hierarchy of scopes explicit.
Source: Notes, ch. 5 — Formatting
If each developer has their own formatting preference, what should be done?
The team should agree on a single style and everyone should follow it.
Source: Notes, ch. 5 — Formatting
What is the difference between an object and a data structure?
Objects hide data behind abstractions and expose functions; data structures expose data and have no meaningful functionality.
Source: Notes, ch. 6 — Objects and Data Structures
What is the trade-off between procedural and object-oriented code?
Procedural makes it easy to add functions without changing the structures, but hard to add new structures; OO makes new classes easy, but new functions hard, since they require changing all classes.
Source: Notes, ch. 6 — Objects and Data Structures
In a geometric shapes system, you expect to add many new operations (area, perimeter, SVG export), but few new shapes. Which approach favors this?
The procedural one (data structures + functions): new functions do not require changing the existing structures.
Source: Notes, ch. 6 — Objects and Data Structures
Is having getters and setters for all attributes data abstraction?
No: abstracting is hiding the implementation and exposing the essence; mechanical getters/setters just expose the structure in different clothes.
Source: Notes, ch. 6 — Objects and Data Structures
What does the Law of Demeter say?
A method of a class C should only call methods of C, of objects it created, of its arguments or of objects held in C's attributes — "don't talk to strangers".
Source: Notes, ch. 6 — Objects and Data Structures
Does ctxt.getOptions().getScratchDir().getAbsolutePath() violate the Law of Demeter?
It depends: if they are objects, yes — the module knows too much about the internal structure; if they are data structures, exposing the structure is natural. Either way, the chaining hurts readability.
Source: Notes, ch. 6 — Objects and Data Structures
Why should hybrids of objects and data structures be avoided?
Because they have meaningful functions and also expose their data: they get the worst of both worlds — hard to add both functions and structures.
Source: Notes, ch. 6 — Objects and Data Structures
What is a DTO?
Data Transfer Object: the purest data structure, with only public variables and no functionality.
Source: Notes, ch. 6 — Objects and Data Structures
Where should business rules go when using Active Record?
In another object: Active Record is a kind of DTO with navigation methods (save, find) and should not contain business rules.
Source: Notes, ch. 6 — Objects and Data Structures
Why use exceptions instead of return codes?
They separate error handling from the main logic; with codes, the caller has to handle the error within its own flow.
Source: Notes, ch. 7 — Error Handling
Why write the try-catch-finally before the rest of the code?
It defines from the start what happens if something fails, making the flow easier to understand; it can be done iteratively: force the exception in a test and then handle it.
Source: Notes, ch. 7 — Error Handling
Why does the author prefer unchecked exceptions in Java?
Checked exceptions violate the open/closed principle: they require declaration in the signature along the whole call chain, and a new exception at a low level causes a cascade of changes.
Source: Notes, ch. 7 — Error Handling
What should an exception contain?
Context: information about the origin of the error and an informative message.
Source: Notes, ch. 7 — Error Handling
How should exception classes be defined, according to ch. 7?
By the needs of whoever catches them, not by their source; often a single class wrapping the third-party API is enough for a region of the code.
Source: Notes, ch. 7 — Error Handling
Code calls a port library that throws three different exceptions, all handled the same way with several catches. What does the author suggest?
Wrap the API in a class of its own that translates the three into a single exception (e.g. PortDeviceFailure), simplifying handling and reducing dependence on the library.
Source: Notes, ch. 7 — Error Handling
What is the Special Case Pattern, and what is it for?
A class that encapsulates the behavior of a special case (e.g. a day with no expenses), so that the normal flow doesn't need to handle the exception inside the main code.
Source: Notes, ch. 7 — Error Handling
Why not return null?
It forces checks everywhere and forgetting just one causes an error; better to throw an exception or return a Special Case Object (e.g. an empty list).
Source: Notes, ch. 7 — Error Handling
getEmployees() returns null when there are no employees. How can this be improved?
Return an empty list; the caller iterates normally without checking for null.
Source: Notes, ch. 7 — Error Handling
Passing null as an argument is less serious than returning it.
False: it is even worse; there is no good way to handle null arguments, the ideal is to forbid them by convention.
Source: Notes, ch. 7 — Error Handling
How should third-party code (such as a generic Map) be handled inside the system?
Encapsulate it in a class of your own with only what the system needs; the details stay hidden and the interaction goes through that class.
Source: Notes, ch. 8 — Boundaries
A payment library is used directly in 40 files and changes its API in the new version. Which practice from ch. 8 would have avoided the problem?
Wrapping it in a class/adapter of your own: only that spot would change, instead of 40 files.
Source: Notes, ch. 8 — Boundaries
What are learning tests?
Unit tests that exercise the third-party API in simple cases in order to learn it; afterwards they remain useful for detecting whether an update broke something.
Source: Notes, ch. 8 — Boundaries
How do you write code that depends on a component that does not exist yet?
Define the ideal interface you would like to have, program against it, and later write an adapter that connects it to the real interface.
Source: Notes, ch. 8 — Boundaries
What are the three laws of TDD?
1) Don't write production code before a failing test; 2) don't write more of a test than is sufficient to fail (not compiling counts); 3) don't write more production code than is sufficient to pass the test.
Source: Notes, ch. 9 — Unit Tests
Following the laws of TDD, test coverage tends to be complete.
True: all production code is born to pass a test; but the volume of tests becomes something to manage.
Source: Notes, ch. 9 — Unit Tests
Why are dirty tests as bad as (or worse than) having no tests?
They become hard to change, start failing without anyone knowing why and turn into a burden, until they are abandoned.
Source: Notes, ch. 9 — Unit Tests
What benefit do tests give the developer?
Flexibility: they allow changing and refactoring without fear of breaking something.
Source: Notes, ch. 9 — Unit Tests
What is the most important characteristic of a clean test?
Readability: clarity, simplicity and no unnecessary detail.
Source: Notes, ch. 9 — Unit Tests
What is the build-operate-check pattern?
Three steps: build up the test data, operate on it and check the result — analogous to given-when-then.
Source: Notes, ch. 9 — Unit Tests
What is the "dual standard" for test code?
Tests don't need to be as efficient as production code (the environments differ), but they need to be just as clean.
Source: Notes, ch. 9 — Unit Tests
What is more important than "one assert per test"?
One concept per test; several asserts are acceptable if they are the minimum needed for that concept.
Source: Notes, ch. 9 — Unit Tests
In the F.I.R.S.T. principles, what does the I stand for?
Independent: a test's result should not depend on another, with no cascading effect.
Source: Notes, ch. 9 — Unit Tests
What do the letters of F.I.R.S.T. stand for?
Fast, Independent, Repeatable (in any environment), Self-validating (pass or fail, no manual analysis) and Timely (written just before the production code).
Source: Notes, ch. 9 — Unit Tests
A test only passes when it runs after another one that populates the database, and someone has to read a log to know whether it worked. Which F.I.R.S.T. principles does it violate?
Independent (it depends on another test) and Self-validating (it requires manual analysis instead of pass/fail).
Source: Notes, ch. 9 — Unit Tests
What is the conventional order of elements in a class?
Public constants, private constants, private instance variables, public functions; private functions right after the public function that uses them.
Source: Notes, ch. 10 — Classes
How is the size of a class measured?
In responsibilities, not lines: it should have few, ideally one.
Source: Notes, ch. 10 — Classes
What does the Single Responsibility Principle say?
A class or module should have one, and only one, reason to change.
Source: Notes, ch. 10 — Classes
A class's description is "manages versions and shows the dashboard". What does this indicate?
That it violates the SRP: the "and" reveals two responsibilities, which should go into separate classes.
Source: Notes, ch. 10 — Classes
What is a class's cohesion?
How tightly its methods and variables are connected: maximum cohesion is when every method uses every variable.
Source: Notes, ch. 10 — Classes
In a class, one group of variables is used only by three methods and another group only by three other methods. What should be done?
Split it into two classes: they are two cohesive sets within a class of low cohesion.
Source: Notes, ch. 10 — Classes
What does the Open-Closed Principle say?
Classes should be open for extension and closed for modification: new features come in by adding code, not by changing existing code.
Source: Notes, ch. 10 — Classes
What does the Dependency Inversion Principle say?
Classes should depend on abstractions, not on concrete details.
Source: Notes, ch. 10 — Classes
A Portfolio class calls a stock exchange quotes API directly, which makes tests slow and unstable. How does the DIP help?
Portfolio comes to depend on an interface (e.g. StockExchange); in production it receives the real implementation, in tests a fake one with fixed values.
Source: Notes, ch. 10 — Classes
Making variables public to make testing easier is a recommended practice.
False: it is a bad idea; the test should go through the encapsulated interface.
Source: Notes, ch. 10 — Classes
What does it mean to separate the construction of a system from its use?
Separating startup (creating and wiring objects) from the runtime logic, for example concentrating construction in main or in factories.
Source: Notes, ch. 11 — Systems
What is dependency injection?
Applying inversion of control to dependency management: the class receives from outside (on instantiation) the objects it needs, instead of creating them.
Source: Notes, ch. 11 — Systems
An OrderService class does self.db = PostgresDB() in its constructor. What problem does this bring, and how does DI solve it?
It couples the class to the concrete implementation and prevents testing with a fake database; with DI, the database is passed in the constructor and main decides which one to use.
Source: Notes, ch. 11 — Systems
What are cross-cutting concerns?
General aspects that cut across the system, such as persistence, logging or security; they should be added non-invasively.
Source: Notes, ch. 11 — Systems
How is the idea of aspect-oriented programming applied in Python?
With decorators: the aspect (e.g. logging) lives in a separate decorator, and the business function stays clean.
Source: Notes, ch. 11 — Systems
Why does modularization by aspects avoid BDUF?
Because it allows the system to grow and change incrementally, without needing a big design defined before starting (Big Design Up Front).
Source: Notes, ch. 11 — Systems
Why postpone decisions until the last possible moment?
To decide with the best information available; modularization also allows decentralized decisions.
Source: Notes, ch. 11 — Systems
What are DSLs for in a system?
Domain-specific languages raise the level of abstraction, making the system more explicit and easing communication with domain experts.
Source: Notes, ch. 11 — Systems
What are Kent Beck's four rules of simple design, in order of priority?
1) Runs all the tests; 2) contains no duplication; 3) expresses the programmer's intent; 4) minimizes the number of classes and methods.
Source: Notes, ch. 12 — Emergence
Why does "runs all the tests" come first and enable the other rules?
Because making the system testable forces small, loosely coupled classes (SRP, DIP), and the tests give the confidence to refactor: eliminate duplication, improve names, reduce coupling.
Source: Notes, ch. 12 — Emergence
How do you eliminate the duplication between size() and isEmpty()?
Implement one in terms of the other: isEmpty() returns 0 == size().
Source: Notes, ch. 12 — Emergence
Which design pattern do the notes point to for eliminating duplication between similar algorithms?
Template Method: the skeleton of the algorithm stays in the base class and the variations in subclasses.
Source: Notes, ch. 12 — Emergence
Why is expressiveness a rule of simple design?
Because the biggest cost of software is maintenance; the clearer the code, the less time to understand it — including for ourselves in the future.
Source: Notes, ch. 12 — Emergence
Minimizing the number of classes and methods is the most important of the four rules.
False: it is the least important; it serves to curb the excess of tiny classes that a dogmatic SRP can produce.
Source: Notes, ch. 12 — Emergence
What does concurrency decouple?
What gets done from when it gets done; in a single thread the two are coupled.
Source: Notes, ch. 13 — Concurrency
Which of these statements about concurrency is true?
The other three are myths listed in the chapter; concurrency changes the design considerably.
Source: Notes, ch. 13 — Concurrency
Why are concurrency bugs so hard?
There are several possible execution paths for the same code, with different results; that is why bugs are not always reproducible.
Source: Notes, ch. 13 — Concurrency
How does the SRP apply to concurrency?
Separate concurrency code from the rest of the code, because it has its own life cycle and challenges.
Source: Notes, ch. 13 — Concurrency
How do you protect data shared between threads?
By limiting the scope: protected critical sections (synchronized in Java, with lock: in Python), and preferring copies of the data and threads as independent as possible.
Source: Notes, ch. 13 — Concurrency
Why should synchronized sections be as small as possible?
Because locks create bottlenecks and contention; the larger the locked section, the more the threads wait.
Source: Notes, ch. 13 — Concurrency
How does the producer-consumer model work?
Producers put tasks into a bounded queue and consumers take them out and execute them; coordination is needed so that no one acts at the wrong time.
Source: Notes, ch. 13 — Concurrency
What is the challenge of the readers-writers model?
Readers can't read while the writer writes and vice versa; it must be balanced so as not to cause starvation on either side.
Source: Notes, ch. 13 — Concurrency
What is the difference between deadlock and livelock, in the dining philosophers problem?
Deadlock: threads wait for one another and none makes progress. Livelock: threads stay active, but keep interrupting each other without progressing.
Source: Notes, ch. 13 — Concurrency
A test of concurrent code fails once and then passes. What should you do?
Not ignore it: it may indicate a real threading problem.
Source: Notes, ch. 13 — Concurrency
How do you force concurrency bugs to show up in tests?
Run with more threads than processors, on different platforms, and vary the execution order with wait/yield/sleep, manually or through automatic instrumentation (jiggling).
Source: Notes, ch. 13 — Concurrency
Before debugging the concurrent part, what must work?
The single-threaded part of the code; and multithreaded code should be pluggable and tunable to run in various configurations.
Source: Notes, ch. 13 — Concurrency
What is the main lesson of the argument parser case study?
Clean code starts dirty and is cleaned afterwards: the first version is never the ideal one, and merely making it work is not the whole job.
Source: Notes, ch. 14 — Successive Refinement
How does TDD support incremental refactoring?
With tests, the system is always working: you move in small steps and only proceed when the tests pass.
Source: Notes, ch. 14 — Successive Refinement
You keep adding argument types to the parser and the code gets more and more tangled. What does ch. 14 recommend?
Stop adding features and refactor now; cleaning code that has been dirty for a long time is much harder.
Source: Notes, ch. 14 — Successive Refinement
What improvements does the author apply to JUnit's ComparisonCompactor?
Improving names, encapsulating conditionals, making temporal coupling explicit, removing the arbitrary +1s with a 0-indexed length and separating analysis and synthesis functions.
Source: Notes, ch. 15 — JUnit Internals
What is the first step in refactoring SerialDate?
Writing tests until there is complete coverage (the original covered about half) and fixing the wrong tests before touching the code.
Source: Notes, ch. 16 — Refactoring SerialDate
What was wrong with the name SerialDate?
"Serial" suggests an implementation, but it is an abstract class; Date or DayDate would be better.
Source: Notes, ch. 16 — Refactoring SerialDate
What change does the author make to MonthConstants?
He replaces the inherited constants class with an Enum, which can also hold the validation of months.
Source: Notes, ch. 16 — Refactoring SerialDate
Which comment smells does ch. 17 list?
Inappropriate information, obsolete, redundant, poorly written and commented-out code.
Source: Notes, ch. 17 — Smells and Heuristics
What do the environment heuristics say about build and tests?
Both should run with a single command.
Source: Notes, ch. 17 — Smells and Heuristics
What is the principle of least surprise?
Functions and classes should implement the behavior another programmer would intuitively expect.
Source: Notes, ch. 17 — Smells and Heuristics
What is feature envy?
When a method is more interested in the variables and functions of another class than in its own; it probably belongs to the other class.
Source: Notes, ch. 17 — Smells and Heuristics
A method of Report makes five calls to getters of Employee to calculate overtime. What smell is this, and what should be done?
Feature envy: the calculation should be a method of Employee.
Source: Notes, ch. 17 — Smells and Heuristics
What is artificial coupling?
Coupling things that don't depend on each other, such as putting enums or general utility functions inside specific classes.
Source: Notes, ch. 17 — Smells and Heuristics
What should be done with magic numbers?
Replace them with named constants, except in obvious cases (like the 2 in 2 * PI * radius).
Source: Notes, ch. 17 — Smells and Heuristics
What heuristic does ch. 17 give about repeated if/else and switch?
Prefer polymorphism to if/else or switch/case chains.
Source: Notes, ch. 17 — Smells and Heuristics
Why is "structure more important than convention"?
Because imposing a structure (e.g. an abstract class with mandatory methods) enforces behavior in a rigid and predictable way; a naming convention can be ignored.
Source: Notes, ch. 17 — Smells and Heuristics
What does encapsulating conditionals mean?
Replacing long and/or expressions with a function with an explanatory name (e.g. if (shouldBeDeleted(timer))).
Source: Notes, ch. 17 — Smells and Heuristics
Three methods must be called in a mandatory order. How do you make this explicit?
Make each one receive the result of the previous one as an argument, so that the order is enforced by the structure, even if it gets a bit more complex.
Source: Notes, ch. 17 — Smells and Heuristics
What does encapsulating boundary conditions mean?
Concentrating adjustments such as +1 and -1 in a single place (for example, a variable nextLevel = level + 1), instead of scattering them.
Source: Notes, ch. 17 — Smells and Heuristics
Where should configurable data, such as configuration constants, live?
At the high level: low-level code receives these values as arguments.
Source: Notes, ch. 17 — Smells and Heuristics
If A uses B and B uses C, what does the transitive navigation heuristic say about A?
A should know nothing about C; it is the Law of Demeter applied to modules.
Source: Notes, ch. 17 — Smells and Heuristics
Why is Modem.dial(phoneNumber) a name at the wrong level of abstraction?
Because it assumes an implementation (a phone line); at an abstract level, a modem connects — something like connect(connectionLocator).
Source: Notes, ch. 17 — Smells and Heuristics
Where should more tests be concentrated, according to the heuristics?
Where bugs have already been found, because bugs tend to congregate.
Source: Notes, ch. 17 — Smells and Heuristics
An ignored test (@Ignore) can reveal an ambiguity about the expected behavior.
True: it points to an open question about what the code should do.
Source: Notes, ch. 17 — Smells and Heuristics
When should a method be static?
Only when it depends on nothing in the object, just on its arguments, and there is no chance it will need polymorphic behavior; when in doubt, not static.
Source: Notes, ch. 17 — Smells and Heuristics
What are explanatory variables?
Intermediate variables with meaningful names that break a calculation into obvious steps.
Source: Notes, ch. 17 — Smells and Heuristics
Why is it not enough for the code to pass the tests?
Because you need to understand the algorithm and know that it is correct, not just observe that it seems to work; often that requires refactoring until it is clear.
Source: Notes, ch. 17 — Smells and Heuristics
Shortcuts: Enter reveals the answer or the options, then goes to the next one · 1–4 answers · Z undoes · E writes · Esc leaves the text box
Transparency note AI was used in this post for: generating the study questions · creating the English version