Clean Code

Clean Code

A Handbook of Agile Software Craftsmanship

de Robert C. Martin (2008)

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.



Notes





Active study

  1. Recall concept · cap-1 ●○○

    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

  2. Recall names-and-dates · cap-1 ●○○

    What does LeBlanc's Law say?

    Reveal answer

    "Later equals never": cleanup put off until later almost never happens.

    Source: Notes, ch. 1 — Clean Code

  3. Recall relationship · cap-1 ●●○

    The manager pushes to deliver faster by sacrificing quality. What does the author say the developer should do?

    Reveal answer

    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

  4. Recall concept · cap-1 ●○○

    Why is readability so central to clean code?

    Reveal answer

    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

  5. Recall concept · cap-1 ●○○

    What is the Boy Scout Rule?

    Reveal answer

    Leave the code cleaner than you found it, with small incremental improvements on each pass.

    Source: Notes, ch. 1 — Clean Code

  6. Recall relationship · cap-1 ●●○

    You are going to fix a bug in a function and notice a variable called d. What does the Boy Scout Rule suggest?

    Reveal answer

    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

  7. True or false detail · cap-1 ●○○

    The book presents a single, agreed-upon definition of clean code.

  8. Recall concept · cap-2 ●○○

    What should a good name communicate?

    Reveal answer

    Intent: the what, how and why of that variable, to the point of making comments unnecessary.

    Source: Notes, ch. 2 — Meaningful Names

  9. Recall relationship · cap-2 ●●○

    Improve: int d; // elapsed time in days.

    Reveal answer

    Use a name that makes the comment unnecessary, such as int elapsedTimeInDays.

    Source: Notes, ch. 2 — Meaningful Names

  10. Recall concept · cap-2 ●●○

    Why avoid calling something that is not a list accountList?

    Reveal answer

    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

  11. True or false detail · cap-2 ●○○

    Using l and O as variable names is problematic because they are confused with 1 and 0.

  12. Recall concept · cap-2 ●●○

    What is the problem with names such as a1/a2 or ProductInfo/ProductData?

    Reveal answer

    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

  13. Recall concept · cap-2 ●○○

    Why use pronounceable names, like customer instead of cstmr?

    Reveal answer

    Because programming is a social activity: pronounceable names can be discussed and remembered easily.

    Source: Notes, ch. 2 — Meaningful Names

  14. Recall concept · cap-2 ●●○

    When are single-letter names (such as i, j) acceptable?

    Reveal answer

    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

  15. Multiple choice relationship · cap-2 ●●○

    Which name is easiest to find with a search in a large project?

  16. Recall concept · cap-2 ●●○

    Which encodings in names does the author say to avoid?

    Reveal answer

    Hungarian notation (type in the name), member prefixes (m_) and the I for interfaces.

    Source: Notes, ch. 2 — Meaningful Names

  17. Multiple choice concept · cap-2 ●○○

    What is the grammatical rule for class and method names?

  18. Recall relationship · cap-2 ●●○

    Why are names like Manager, Processor or Info bad signs in a class?

    Reveal answer

    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

  19. Recall concept · cap-2 ●●○

    What does "one word per concept" mean?

    Reveal answer

    Always using the same term for the same idea — not mixing get, fetch and retrieve for equivalent operations.

    Source: Notes, ch. 2 — Meaningful Names

  20. Recall relationship · cap-2 ●●●

    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?

    Reveal answer

    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

  21. Recall concept · cap-2 ●●○

    Which domain should names come from: the solution or the problem?

    Reveal answer

    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

  22. Recall concept · cap-2 ●●○

    When should you add context to a name, like addrFirstName?

    Reveal answer

    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

  23. True or false detail · cap-2 ●○○

    The author recommends humorous names to make code memorable.

  24. Recall concept · cap-3 ●○○

    What is the ideal size of a function for the author?

    Reveal answer

    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

  25. Recall concept · cap-3 ●○○

    What is the fundamental rule about what a function should do?

    Reveal answer

    Do one thing only, do it well, and do only that.

    Source: Notes, ch. 3 — Functions

  26. Recall concept · cap-3 ●●○

    What does keeping one level of abstraction per function mean?

    Reveal answer

    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

  27. Recall relationship · cap-3 ●●●

    A function generateReport() calls fetchData(), format() and, in between, does manual string index manipulation. What is wrong?

    Reveal answer

    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

  28. Recall concept · cap-3 ●●●

    What should be done with switch statements, according to ch. 3?

    Reveal answer

    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

  29. Recall concept · cap-3 ●○○

    Is it bad to have long function names?

    Reveal answer

    No: a long, descriptive name is better than a short, cryptic one; choosing well may take several attempts.

    Source: Notes, ch. 3 — Functions

  30. Recall concept · cap-3 ●○○

    What is the ideal number of arguments for a function?

    Reveal answer

    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

  31. Recall relationship · cap-3 ●●○

    Why do many arguments make testing harder?

    Reveal answer

    Because they multiply the input combinations that need to be covered.

    Source: Notes, ch. 3 — Functions

  32. Recall concept · cap-3 ●●○

    Why are boolean (flag) arguments a terrible idea?

    Reveal answer

    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

  33. Recall relationship · cap-3 ●●○

    Conceptually refactor render(page, isSuite).

    Reveal answer

    Split it into two functions with clear names, such as renderForSuite(page) and renderForSingleTest(page).

    Source: Notes, ch. 3 — Functions

  34. Recall concept · cap-3 ●●○

    What should you do when a function needs three or more related arguments?

    Reveal answer

    Group them into their own object (e.g. Point instead of x, y) and pass that object.

    Source: Notes, ch. 3 — Functions

  35. Recall detail · cap-3 ●●●

    What are the acceptable forms of monadic function?

    Reveal answer

    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

  36. Recall concept · cap-3 ●●○

    Why should functions not have side effects?

    Reveal answer

    Because they do something hidden beyond what the name promises, creating obfuscation and temporal coupling between actions.

    Source: Notes, ch. 3 — Functions

  37. Recall relationship · cap-3 ●●●

    checkPassword(user, pass) validates the password and, if correct, initializes the session. What is the problem and the solution?

    Reveal answer

    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

  38. Recall concept · cap-3 ●●○

    Why avoid output arguments (modifying the argument in place)?

    Reveal answer

    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

  39. Recall concept · cap-3 ●●○

    What does the command-query separation principle say?

    Reveal answer

    A function should either do something (command) or answer something (query), never both.

    Source: Notes, ch. 3 — Functions

  40. Recall relationship · cap-3 ●●●

    Why is if (set("username", "unclebob")) confusing, and how do you fix it?

    Reveal answer

    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

  41. Recall relationship · cap-3 ●●○

    Why prefer exceptions to error codes?

    Reveal answer

    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

  42. Recall concept · cap-3 ●●○

    How should a function with try/except be structured?

    Reveal answer

    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

  43. Recall concept · cap-3 ●○○

    Why is avoiding duplication so important?

    Reveal answer

    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

  44. True or false relationship · cap-3 ●●○

    The author requires a single return and no break/continue in every function, without exception.

  45. Recall relationship · cap-3 ●●○

    How does the author say one arrives at functions like these?

    Reveal answer

    Through iterative refinement: nobody writes like this the first time; you write, test and keep refactoring.

    Source: Notes, ch. 3 — Functions

  46. Recall concept · cap-4 ●○○

    Why does the author say comments are a necessary evil?

    Reveal answer

    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

  47. Recall relationship · cap-4 ●●○

    Improve: // check whether the employee is eligible for full benefits followed by if ((employee.flags & HOURLY_FLAG) && (employee.age > 65)).

    Reveal answer

    Replace the comment with a function with an explanatory name: if (employee.isEligibleForFullBenefits()).

    Source: Notes, ch. 4 — Comments

  48. True or false concept · cap-4 ●○○

    A bad comment is better than no comment.

  49. Multiple choice detail · cap-4 ●●○

    Which of these is considered a good comment?

  50. Recall concept · cap-4 ●●○

    Name types of acceptable comments.

    Reveal answer

    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

  51. Recall relationship · cap-4 ●●○

    Are TODO comments acceptable without restriction?

    Reveal answer

    No: they serve for future tasks, but they don't justify leaving bad code in the system.

    Source: Notes, ch. 4 — Comments

  52. Recall concept · cap-4 ●●○

    Why not leave commented-out code?

    Reveal answer

    Others are afraid to delete it and it piles up; Git already keeps the old code.

    Source: Notes, ch. 4 — Comments

  53. Recall relationship · cap-4 ●○○

    Why have change-log and attribution comments become bad?

    Reveal answer

    Because version control (Git) already records who changed what and when.

    Source: Notes, ch. 4 — Comments

  54. Recall relationship · cap-4 ●●○

    What does the author think of requiring a docstring on every function?

    Reveal answer

    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

  55. Recall concept · cap-4 ●●●

    What is a comment with nonlocal information?

    Reveal answer

    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

  56. Recall relationship · cap-4 ●●○

    What do closing brace comments (} // end while) indicate?

    Reveal answer

    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

  57. Recall concept · cap-5 ●○○

    What is the goal of code formatting?

    Reveal answer

    Communication: showing care and making the code readable, with consistent rules — not rigidity for its own sake.

    Source: Notes, ch. 5 — Formatting

  58. Recall concept · cap-5 ●●○

    What is the newspaper metaphor for formatting?

    Reveal answer

    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

  59. Recall detail · cap-5 ●●○

    What file size do the notes suggest as good?

    Reveal answer

    Somewhere between 200 and 500 lines, although it depends; smaller files are easier to understand.

    Source: Notes, ch. 5 — Formatting

  60. Recall concept · cap-5 ●●○

    What is conceptual affinity in vertical formatting?

    Reveal answer

    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

  61. Recall relationship · cap-5 ●●○

    How should a function that calls another be positioned?

    Reveal answer

    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

  62. Recall concept · cap-5 ●●○

    Where should local and instance variables be declared?

    Reveal answer

    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

  63. Recall detail · cap-5 ●○○

    What line width does ch. 5 consider excessive?

    Reveal answer

    More than 120 characters; common limits are 80, 100 or 120.

    Source: Notes, ch. 5 — Formatting

  64. Recall relationship · cap-5 ●●●

    Why does the author advise against aligning declarations in columns?

    Reveal answer

    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

  65. True or false relationship · cap-5 ●●○

    For short ifs and loops, it is acceptable to collapse the indentation onto one line.

  66. Recall concept · cap-5 ●○○

    If each developer has their own formatting preference, what should be done?

    Reveal answer

    The team should agree on a single style and everyone should follow it.

    Source: Notes, ch. 5 — Formatting

  67. Recall concept · cap-6 ●●○

    What is the difference between an object and a data structure?

    Reveal answer

    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

  68. Recall concept · relationship · cap-6 ●●●

    What is the trade-off between procedural and object-oriented code?

    Reveal answer

    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

  69. Recall relationship · cap-6 ●●●

    In a geometric shapes system, you expect to add many new operations (area, perimeter, SVG export), but few new shapes. Which approach favors this?

    Reveal answer

    The procedural one (data structures + functions): new functions do not require changing the existing structures.

    Source: Notes, ch. 6 — Objects and Data Structures

  70. Recall concept · cap-6 ●●○

    Is having getters and setters for all attributes data abstraction?

    Reveal answer

    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

  71. Recall concept · cap-6 ●●○

    What does the Law of Demeter say?

    Reveal answer

    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

  72. Recall relationship · cap-6 ●●●

    Does ctxt.getOptions().getScratchDir().getAbsolutePath() violate the Law of Demeter?

    Reveal answer

    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

  73. Recall concept · cap-6 ●●○

    Why should hybrids of objects and data structures be avoided?

    Reveal answer

    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

  74. Recall concept · cap-6 ●○○

    What is a DTO?

    Reveal answer

    Data Transfer Object: the purest data structure, with only public variables and no functionality.

    Source: Notes, ch. 6 — Objects and Data Structures

  75. Recall relationship · cap-6 ●●○

    Where should business rules go when using Active Record?

    Reveal answer

    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

  76. Recall concept · cap-7 ●○○

    Why use exceptions instead of return codes?

    Reveal answer

    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

  77. Recall concept · cap-7 ●●○

    Why write the try-catch-finally before the rest of the code?

    Reveal answer

    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

  78. Recall relationship · cap-7 ●●●

    Why does the author prefer unchecked exceptions in Java?

    Reveal answer

    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

  79. Recall concept · cap-7 ●○○

    What should an exception contain?

    Reveal answer

    Context: information about the origin of the error and an informative message.

    Source: Notes, ch. 7 — Error Handling

  80. Recall concept · cap-7 ●●●

    How should exception classes be defined, according to ch. 7?

    Reveal answer

    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

  81. Recall relationship · cap-7 ●●●

    Code calls a port library that throws three different exceptions, all handled the same way with several catches. What does the author suggest?

    Reveal answer

    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

  82. Recall concept · cap-7 ●●○

    What is the Special Case Pattern, and what is it for?

    Reveal answer

    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

  83. Recall concept · cap-7 ●●○

    Why not return null?

    Reveal answer

    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

  84. Recall relationship · cap-7 ●●○

    getEmployees() returns null when there are no employees. How can this be improved?

    Reveal answer

    Return an empty list; the caller iterates normally without checking for null.

    Source: Notes, ch. 7 — Error Handling

  85. True or false relationship · cap-7 ●●○

    Passing null as an argument is less serious than returning it.

  86. Recall concept · cap-8 ●●○

    How should third-party code (such as a generic Map) be handled inside the system?

    Reveal answer

    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

  87. Recall relationship · cap-8 ●●●

    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?

    Reveal answer

    Wrapping it in a class/adapter of your own: only that spot would change, instead of 40 files.

    Source: Notes, ch. 8 — Boundaries

  88. Recall concept · cap-8 ●●○

    What are learning tests?

    Reveal answer

    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

  89. Recall relationship · cap-8 ●●●

    How do you write code that depends on a component that does not exist yet?

    Reveal answer

    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

  90. Recall concept · cap-9 ●●○

    What are the three laws of TDD?

    Reveal answer

    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

  91. True or false relationship · cap-9 ●○○

    Following the laws of TDD, test coverage tends to be complete.

  92. Recall relationship · cap-9 ●●○

    Why are dirty tests as bad as (or worse than) having no tests?

    Reveal answer

    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

  93. Recall concept · cap-9 ●●○

    What benefit do tests give the developer?

    Reveal answer

    Flexibility: they allow changing and refactoring without fear of breaking something.

    Source: Notes, ch. 9 — Unit Tests

  94. Recall concept · cap-9 ●○○

    What is the most important characteristic of a clean test?

    Reveal answer

    Readability: clarity, simplicity and no unnecessary detail.

    Source: Notes, ch. 9 — Unit Tests

  95. Recall concept · cap-9 ●●○

    What is the build-operate-check pattern?

    Reveal answer

    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

  96. Recall concept · cap-9 ●●○

    What is the "dual standard" for test code?

    Reveal answer

    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

  97. Recall concept · cap-9 ●●○

    What is more important than "one assert per test"?

    Reveal answer

    One concept per test; several asserts are acceptable if they are the minimum needed for that concept.

    Source: Notes, ch. 9 — Unit Tests

  98. Multiple choice concept · cap-9 ●●○

    In the F.I.R.S.T. principles, what does the I stand for?

  99. Recall concept · cap-9 ●●○

    What do the letters of F.I.R.S.T. stand for?

    Reveal answer

    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

  100. Recall relationship · cap-9 ●●●

    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?

    Reveal answer

    Independent (it depends on another test) and Self-validating (it requires manual analysis instead of pass/fail).

    Source: Notes, ch. 9 — Unit Tests

  101. Recall detail · cap-10 ●●○

    What is the conventional order of elements in a class?

    Reveal answer

    Public constants, private constants, private instance variables, public functions; private functions right after the public function that uses them.

    Source: Notes, ch. 10 — Classes

  102. Recall concept · cap-10 ●○○

    How is the size of a class measured?

    Reveal answer

    In responsibilities, not lines: it should have few, ideally one.

    Source: Notes, ch. 10 — Classes

  103. Recall concept · cap-10 ●○○

    What does the Single Responsibility Principle say?

    Reveal answer

    A class or module should have one, and only one, reason to change.

    Source: Notes, ch. 10 — Classes

  104. Recall relationship · cap-10 ●●○

    A class's description is "manages versions and shows the dashboard". What does this indicate?

    Reveal answer

    That it violates the SRP: the "and" reveals two responsibilities, which should go into separate classes.

    Source: Notes, ch. 10 — Classes

  105. Recall concept · cap-10 ●●○

    What is a class's cohesion?

    Reveal answer

    How tightly its methods and variables are connected: maximum cohesion is when every method uses every variable.

    Source: Notes, ch. 10 — Classes

  106. Recall relationship · cap-10 ●●●

    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?

    Reveal answer

    Split it into two classes: they are two cohesive sets within a class of low cohesion.

    Source: Notes, ch. 10 — Classes

  107. Recall concept · cap-10 ●●○

    What does the Open-Closed Principle say?

    Reveal answer

    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

  108. Recall concept · cap-10 ●●○

    What does the Dependency Inversion Principle say?

    Reveal answer

    Classes should depend on abstractions, not on concrete details.

    Source: Notes, ch. 10 — Classes

  109. Recall relationship · cap-10 ●●●

    A Portfolio class calls a stock exchange quotes API directly, which makes tests slow and unstable. How does the DIP help?

    Reveal answer

    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

  110. True or false relationship · cap-10 ●●○

    Making variables public to make testing easier is a recommended practice.

  111. Recall concept · cap-11 ●●○

    What does it mean to separate the construction of a system from its use?

    Reveal answer

    Separating startup (creating and wiring objects) from the runtime logic, for example concentrating construction in main or in factories.

    Source: Notes, ch. 11 — Systems

  112. Recall concept · cap-11 ●●○

    What is dependency injection?

    Reveal answer

    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

  113. Recall relationship · cap-11 ●●●

    An OrderService class does self.db = PostgresDB() in its constructor. What problem does this bring, and how does DI solve it?

    Reveal answer

    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

  114. Recall concept · cap-11 ●●○

    What are cross-cutting concerns?

    Reveal answer

    General aspects that cut across the system, such as persistence, logging or security; they should be added non-invasively.

    Source: Notes, ch. 11 — Systems

  115. Recall relationship · cap-11 ●●●

    How is the idea of aspect-oriented programming applied in Python?

    Reveal answer

    With decorators: the aspect (e.g. logging) lives in a separate decorator, and the business function stays clean.

    Source: Notes, ch. 11 — Systems

  116. Recall relationship · cap-11 ●●○

    Why does modularization by aspects avoid BDUF?

    Reveal answer

    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

  117. Recall concept · cap-11 ●●○

    Why postpone decisions until the last possible moment?

    Reveal answer

    To decide with the best information available; modularization also allows decentralized decisions.

    Source: Notes, ch. 11 — Systems

  118. Recall concept · cap-11 ●●○

    What are DSLs for in a system?

    Reveal answer

    Domain-specific languages raise the level of abstraction, making the system more explicit and easing communication with domain experts.

    Source: Notes, ch. 11 — Systems

  119. Recall concept · cap-12 ●●○

    What are Kent Beck's four rules of simple design, in order of priority?

    Reveal answer

    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

  120. Recall relationship · cap-12 ●●●

    Why does "runs all the tests" come first and enable the other rules?

    Reveal answer

    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

  121. Recall relationship · cap-12 ●●○

    How do you eliminate the duplication between size() and isEmpty()?

    Reveal answer

    Implement one in terms of the other: isEmpty() returns 0 == size().

    Source: Notes, ch. 12 — Emergence

  122. Recall concept · cap-12 ●●●

    Which design pattern do the notes point to for eliminating duplication between similar algorithms?

    Reveal answer

    Template Method: the skeleton of the algorithm stays in the base class and the variations in subclasses.

    Source: Notes, ch. 12 — Emergence

  123. Recall relationship · cap-12 ●●○

    Why is expressiveness a rule of simple design?

    Reveal answer

    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

  124. True or false detail · cap-12 ●●○

    Minimizing the number of classes and methods is the most important of the four rules.

  125. Recall concept · cap-13 ●●○

    What does concurrency decouple?

    Reveal answer

    What gets done from when it gets done; in a single thread the two are coupled.

    Source: Notes, ch. 13 — Concurrency

  126. Multiple choice concept · cap-13 ●●○

    Which of these statements about concurrency is true?

  127. Recall relationship · cap-13 ●●○

    Why are concurrency bugs so hard?

    Reveal answer

    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

  128. Recall concept · cap-13 ●●○

    How does the SRP apply to concurrency?

    Reveal answer

    Separate concurrency code from the rest of the code, because it has its own life cycle and challenges.

    Source: Notes, ch. 13 — Concurrency

  129. Recall concept · cap-13 ●●○

    How do you protect data shared between threads?

    Reveal answer

    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

  130. Recall relationship · cap-13 ●●●

    Why should synchronized sections be as small as possible?

    Reveal answer

    Because locks create bottlenecks and contention; the larger the locked section, the more the threads wait.

    Source: Notes, ch. 13 — Concurrency

  131. Recall concept · cap-13 ●●○

    How does the producer-consumer model work?

    Reveal answer

    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

  132. Recall concept · cap-13 ●●●

    What is the challenge of the readers-writers model?

    Reveal answer

    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

  133. Recall concept · cap-13 ●●●

    What is the difference between deadlock and livelock, in the dining philosophers problem?

    Reveal answer

    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

  134. Recall relationship · cap-13 ●●○

    A test of concurrent code fails once and then passes. What should you do?

    Reveal answer

    Not ignore it: it may indicate a real threading problem.

    Source: Notes, ch. 13 — Concurrency

  135. Recall concept · cap-13 ●●●

    How do you force concurrency bugs to show up in tests?

    Reveal answer

    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

  136. Recall relationship · cap-13 ●●○

    Before debugging the concurrent part, what must work?

    Reveal answer

    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

  137. Recall concept · cap-14 ●●○

    What is the main lesson of the argument parser case study?

    Reveal answer

    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

  138. Recall relationship · cap-14 ●●○

    How does TDD support incremental refactoring?

    Reveal answer

    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

  139. Recall relationship · cap-14 ●●●

    You keep adding argument types to the parser and the code gets more and more tangled. What does ch. 14 recommend?

    Reveal answer

    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

  140. Recall detail · cap-15 ●●●

    What improvements does the author apply to JUnit's ComparisonCompactor?

    Reveal answer

    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

  141. Recall relationship · cap-16 ●●○

    What is the first step in refactoring SerialDate?

    Reveal answer

    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

  142. Recall relationship · cap-16 ●●○

    What was wrong with the name SerialDate?

    Reveal answer

    "Serial" suggests an implementation, but it is an abstract class; Date or DayDate would be better.

    Source: Notes, ch. 16 — Refactoring SerialDate

  143. Recall relationship · cap-16 ●●○

    What change does the author make to MonthConstants?

    Reveal answer

    He replaces the inherited constants class with an Enum, which can also hold the validation of months.

    Source: Notes, ch. 16 — Refactoring SerialDate

  144. Recall detail · cap-17 ●○○

    Which comment smells does ch. 17 list?

    Reveal answer

    Inappropriate information, obsolete, redundant, poorly written and commented-out code.

    Source: Notes, ch. 17 — Smells and Heuristics

  145. Recall concept · cap-17 ●●○

    What do the environment heuristics say about build and tests?

    Reveal answer

    Both should run with a single command.

    Source: Notes, ch. 17 — Smells and Heuristics

  146. Recall concept · cap-17 ●●○

    What is the principle of least surprise?

    Reveal answer

    Functions and classes should implement the behavior another programmer would intuitively expect.

    Source: Notes, ch. 17 — Smells and Heuristics

  147. Recall concept · cap-17 ●●●

    What is feature envy?

    Reveal answer

    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

  148. Recall relationship · cap-17 ●●●

    A method of Report makes five calls to getters of Employee to calculate overtime. What smell is this, and what should be done?

    Reveal answer

    Feature envy: the calculation should be a method of Employee.

    Source: Notes, ch. 17 — Smells and Heuristics

  149. Recall concept · cap-17 ●●●

    What is artificial coupling?

    Reveal answer

    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

  150. Recall concept · cap-17 ●○○

    What should be done with magic numbers?

    Reveal answer

    Replace them with named constants, except in obvious cases (like the 2 in 2 * PI * radius).

    Source: Notes, ch. 17 — Smells and Heuristics

  151. Recall relationship · cap-17 ●●○

    What heuristic does ch. 17 give about repeated if/else and switch?

    Reveal answer

    Prefer polymorphism to if/else or switch/case chains.

    Source: Notes, ch. 17 — Smells and Heuristics

  152. Recall relationship · cap-17 ●●●

    Why is "structure more important than convention"?

    Reveal answer

    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

  153. Recall concept · cap-17 ●●○

    What does encapsulating conditionals mean?

    Reveal answer

    Replacing long and/or expressions with a function with an explanatory name (e.g. if (shouldBeDeleted(timer))).

    Source: Notes, ch. 17 — Smells and Heuristics

  154. Recall relationship · cap-17 ●●●

    Three methods must be called in a mandatory order. How do you make this explicit?

    Reveal answer

    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

  155. Recall concept · cap-17 ●●○

    What does encapsulating boundary conditions mean?

    Reveal answer

    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

  156. Recall concept · cap-17 ●●○

    Where should configurable data, such as configuration constants, live?

    Reveal answer

    At the high level: low-level code receives these values as arguments.

    Source: Notes, ch. 17 — Smells and Heuristics

  157. Recall relationship · cap-17 ●●●

    If A uses B and B uses C, what does the transitive navigation heuristic say about A?

    Reveal answer

    A should know nothing about C; it is the Law of Demeter applied to modules.

    Source: Notes, ch. 17 — Smells and Heuristics

  158. Recall relationship · cap-17 ●●●

    Why is Modem.dial(phoneNumber) a name at the wrong level of abstraction?

    Reveal answer

    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

  159. Recall relationship · cap-17 ●●○

    Where should more tests be concentrated, according to the heuristics?

    Reveal answer

    Where bugs have already been found, because bugs tend to congregate.

    Source: Notes, ch. 17 — Smells and Heuristics

  160. True or false relationship · cap-17 ●●○

    An ignored test (@Ignore) can reveal an ambiguity about the expected behavior.

  161. Recall concept · cap-17 ●●○

    When should a method be static?

    Reveal answer

    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

  162. Recall concept · cap-17 ●○○

    What are explanatory variables?

    Reveal answer

    Intermediate variables with meaningful names that break a calculation into obvious steps.

    Source: Notes, ch. 17 — Smells and Heuristics

  163. Recall relationship · cap-17 ●●●

    Why is it not enough for the code to pass the tests?

    Reveal answer

    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

See all questions (163)

Transparency note AI was used in this post for: generating the study questions · creating the English version