{"id":84,"date":"2025-03-29T17:24:12","date_gmt":"2025-03-29T12:24:12","guid":{"rendered":"https:\/\/sagadenov.com\/?p=84"},"modified":"2025-03-30T23:16:44","modified_gmt":"2025-03-30T18:16:44","slug":"clean-code-by-robert-c-martindraft","status":"publish","type":"post","link":"https:\/\/sagadenov.com\/?p=84","title":{"rendered":"Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin"},"content":{"rendered":"\n<blockquote class=\"wp-block-quote is-layout-flow wp-block-quote-is-layout-flow\">\n<p>\u201cClean code is not code that follows rules. It\u2019s code that\u2019s written with care.\u201d<br>\u2014 Robert C. Martin\u200b<\/p>\n<\/blockquote>\n\n\n\n<p>Robert Martin argues that bad code slows everything down \u2014 it blocks team progress, makes changes risky, and breaks the product.<br>In contrast, <em>clean code<\/em> is:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>readable;<\/li>\n\n\n\n<li>logically structured;<\/li>\n\n\n\n<li>covered with tests;<\/li>\n\n\n\n<li>free of duplication;<\/li>\n\n\n\n<li>understandable without comments.<\/li>\n<\/ul>\n\n\n\n<p>But most importantly \u2014 it\u2019s written as if the author <strong>cared<\/strong>.<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p><strong>Key takeaways<\/strong>:<\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>A function should do one thing<\/strong><br>If a function does more than one thing \u2014 that\u2019s a red flag. <strong>Better to split than to explain with a flag.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>render(true); \/\/ what does this even mean?\n\n\/\/ Better\nrenderForSuite();\nrenderForSingleTest();<span style=\"background-color: initial; font-family: inherit; color: var(--wp--preset--color--contrast-2); font-size: var(--wp--preset--font-size--medium);\"><\/span><\/code><\/code><\/pre>\n\n\n\n<p><strong>Clear and self-explanatory.<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Comments are the last resort<\/strong><br>If you need a comment to explain something, the code should probably be rewritten.<\/p>\n\n\n\n<p>Martin also emphasizes that code should explain itself. He challenges the traditional idea that documentation lives separately in Confluence or Wiki pages. Instead, he insists that clear naming and structure are documentation. If you\u2019re writing an API, make it self-explanatory \u2014 your users shouldn\u2019t need to read a manual. He writes: \u201cThe proper use of functions and naming should make the code self-documenting.\u201d<br>One of the best examples in the book shows how deeply nested logic is turned into a <strong>clean, readable method<\/strong>.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><code>if (pageData.hasAttribute(\"Test\")) {\n  if (includeSuiteSetup) {\n    WikiPage suiteSetup = ...\n    buffer.append(\"!include -setup .\")\n  }\n  ...\n}\n\/\/Better\npublic static String renderPageWithSetupsAndTeardowns(...) {\n  includeSetupPages(...);\n  ...\n  includeTeardownPages(...);\n}<span style=\"background-color: initial; font-family: inherit; color: var(--wp--preset--color--contrast-2); font-size: var(--wp--preset--font-size--medium);\"><\/span><\/code><\/code><\/pre>\n\n\n\n<p><strong>Instead of layers of logic \u2014 clear, named actions.<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>The Boy Scout Rule<\/strong><br>If you open a file \u2014 leave it cleaner than you found it. <strong>Even a small rename or removed comment is progress.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Before\nint d; \/\/ elapsed time in days\n\n\/\/ After\nint elapsedDays;<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Flag arguments are a code smell<\/strong><br>They mean the function does more than one thing. <strong>Split into separate methods \u2014 it improves clarity and reduces branching.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Bad\nsave(data, true); \/\/ true = draft?\n\n\/\/ Better\nsaveDraft(data);\nsaveFinalVersion(data);<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Formatting = thinking structure<\/strong><br>Martin promotes the <strong>newspaper metaphor<\/strong>: start with headlines, then dive into details.<br>Code should be <strong>readable top-down like an article.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Bad (details come first)\nint x = 5;\n...\nmainLogic();\n\n\/\/ Better (headline first)\npublic void processOrder() {\n  validate();\n  calculateTotals();\n  notifyCustomer();\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Formatting is communication, not decoration<\/strong><br>Code is read far more often than it is written. <strong>That\u2019s why formatting matters \u2014 it guides the reader\u2019s eye.<\/strong><\/p>\n\n\n\n<p>Martin refers to the newspaper metaphor:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>first<\/strong>, show high-level structure (like imports and declarations)<\/li>\n\n\n\n<li><strong>then<\/strong>, the overview (top-level functions)<\/li>\n\n\n\n<li><strong>only then<\/strong>, the details<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Bad formatting \u2014 hard to read\npublic void calculate(){int sum=0;for(int i=0;i&lt;orders.length;i++){sum+=orders&#91;i].getAmount();}System.out.println(sum);}\n\n\/\/ Better formatting \u2014 communicates intent\npublic void calculate() {\n  int sum = 0;\n  for (int i = 0; i &lt; orders.length; i++) {\n    sum += orders&#91;i].getAmount();\n  }\n  System.out.println(sum);\n}<\/code><\/pre>\n\n\n\n<p><strong>Good formatting supports understanding, not just aesthetics.<\/strong><\/p>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Tests should be F.I.R.S.T.<\/strong><\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Fast<\/strong> \u00abTests should run quickly.\u00bb<\/li>\n\n\n\n<li><strong>Independent<\/strong> \u00abTests should not depend on each other.\u00bb<\/li>\n\n\n\n<li><strong>Repeatable<\/strong> \u00abThey should run in any environment and produce the same result.\u00bb<\/li>\n\n\n\n<li><strong>Self-validating<\/strong> \u00abA test should have a boolean output. It either passes or fails.\u00bb<\/li>\n\n\n\n<li><strong>Timely<\/strong> \u2014 written before the implementation, not after \u00abThey need to be written before the production code.\u00bb<\/li>\n<\/ol>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Small, constant improvements matter<\/strong><br>You don\u2019t need to clean everything at once.<br>Martin encourages many <strong>small, safe edits<\/strong> \u2014 like renaming a variable, simplifying a loop, or extracting a method.<br><strong>Each improvement compounds.<\/strong> Over time, your codebase becomes easier to work with.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Before\nfor (int i = 0; i &lt; list.size(); i++) {\n  System.out.println(list.get(i));\n}\n\n\/\/ After\nfor (String item : list) {\n  System.out.println(item);\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Classes should be small and focused<\/strong><br>The size of a class is not measured by lines of code but by the <strong>number of responsibilities<\/strong> it handles.<br>If it does more than one thing \u2014 it\u2019s harder to test, understand, and change.<br><strong>Split responsibilities into separate classes<\/strong>, each with a single reason to change.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Bad\nclass ReportManager {\n  void renderReport() { ... }\n  void calculateTotals() { ... }\n}\n\n\/\/ Better\nclass ReportRenderer { ... }\nclass ReportCalculator { ... }<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Avoid duplication \u2014 abstract instead<\/strong><br>Repetition is a sign of <strong>missing abstraction<\/strong>.<br>When you see the same logic or structure more than once, it\u2019s time to extract a method, use a design pattern, or rethink your structure.<br><strong>Duplication increases maintenance cost and hides bugs.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Before\nsendEmailToAdmin();\nsendEmailToUser();\nsendEmailToSupport();\n\n\/\/ After\nsendEmail(\"admin\");\nsendEmail(\"user\");\nsendEmail(\"support\");<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Don\u2019t return or pass null<\/strong><br>Returning <code>null<\/code> forces the caller to write defensive code.<br>It increases the risk of runtime errors and clutters logic.<br>Instead, <strong>return empty objects, empty collections, or use <code>Optional<\/code> types<\/strong> when appropriate.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Bad\nUser user = repo.findById(id);\nif (user != null) {\n  sendEmail(user);\n}\n\n\/\/ Better\nrepo.findById(id).ifPresent(this::sendEmail);<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Prefer exceptions over error codes<\/strong><br>Returning error codes pollutes the main logic and forces repetitive checks.<br>Clean code handles errors using <strong>exceptions \u2014 separating error-handling paths<\/strong> from normal execution.<br><strong>Keep the \u201chappy path\u201d clear and linear.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Bad\nif (save(user) == -1) {\n  log(\"Failed\");\n}\n\n\/\/ Better\ntry {\n  save(user);\n} catch (SaveFailedException e) {\n  log(\"Failed\");\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<p>\u2022 <strong>Inject dependencies \u2014 don\u2019t create them<\/strong><br>Code should not be responsible for instantiating its own dependencies.<br>Instead, they should be provided from the outside (constructor injection, factory, or IoC container).<br><strong>This reduces coupling and makes testing easier.<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ Bad\nclass UserController {\n  private EmailService service = new EmailService();\n}\n\n\/\/ Better\nclass UserController {\n  private final EmailService service;\n\n  public UserController(EmailService service) {\n    this.service = service;\n  }\n}<\/code><\/pre>\n\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n\n\n<h3 class=\"wp-block-heading\">Final thoughts<\/h3>\n\n\n\n<p><em>Clean Code<\/em> isn\u2019t about code style \u2014 it\u2019s about <strong>how you think as a software engineer<\/strong>.<br>It encourages care, discipline, and long-term thinking.<br>After reading it, you\u2019ll start to question shortcuts like \u201cit works for now\u201d \u2014 and you\u2019ll build the habit of writing code that others (and your future self) will appreciate.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u201cClean code is not code that follows rules. It\u2019s code that\u2019s written with care.\u201d\u2014 Robert C. Martin\u200b Robert Martin argues that bad code slows everything down \u2014 it blocks team progress, makes changes risky, and breaks the product.In contrast, clean code is: But most importantly \u2014 it\u2019s written as if the author cared. Key takeaways: [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-84","post","type-post","status-publish","format-standard","hentry","category-about-my-read-books"],"_links":{"self":[{"href":"https:\/\/sagadenov.com\/index.php?rest_route=\/wp\/v2\/posts\/84","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sagadenov.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sagadenov.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sagadenov.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sagadenov.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=84"}],"version-history":[{"count":24,"href":"https:\/\/sagadenov.com\/index.php?rest_route=\/wp\/v2\/posts\/84\/revisions"}],"predecessor-version":[{"id":166,"href":"https:\/\/sagadenov.com\/index.php?rest_route=\/wp\/v2\/posts\/84\/revisions\/166"}],"wp:attachment":[{"href":"https:\/\/sagadenov.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=84"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sagadenov.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=84"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sagadenov.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=84"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}