Files
org_roam/output/20250727221512-clean_code.html
2025-12-28 20:55:38 +00:00

1390 lines
45 KiB
HTML
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<!-- 2025-12-28 Sun 20:54 -->
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>clean-code</title>
<meta name="generator" content="Org Mode" />
<style type="text/css">
#content { max-width: 60em; margin: auto; }
.title { text-align: center;
margin-bottom: .2em; }
.subtitle { text-align: center;
font-size: medium;
font-weight: bold;
margin-top:0; }
.todo { font-family: monospace; color: red; }
.done { font-family: monospace; color: green; }
.priority { font-family: monospace; color: orange; }
.tag { background-color: #eee; font-family: monospace;
padding: 2px; font-size: 80%; font-weight: normal; }
.timestamp { color: #bebebe; }
.timestamp-kwd { color: #5f9ea0; }
.org-right { margin-left: auto; margin-right: 0px; text-align: right; }
.org-left { margin-left: 0px; margin-right: auto; text-align: left; }
.org-center { margin-left: auto; margin-right: auto; text-align: center; }
.underline { text-decoration: underline; }
#postamble p, #preamble p { font-size: 90%; margin: .2em; }
p.verse { margin-left: 3%; }
pre {
border: 1px solid #e6e6e6;
border-radius: 3px;
background-color: #f2f2f2;
padding: 8pt;
font-family: monospace;
overflow: auto;
margin: 1.2em;
}
pre.src {
position: relative;
overflow: auto;
}
pre.src:before {
display: none;
position: absolute;
top: -8px;
right: 12px;
padding: 3px;
color: #555;
background-color: #f2f2f299;
}
pre.src:hover:before { display: inline; margin-top: 14px;}
/* Languages per Org manual */
pre.src-asymptote:before { content: 'Asymptote'; }
pre.src-awk:before { content: 'Awk'; }
pre.src-authinfo::before { content: 'Authinfo'; }
pre.src-C:before { content: 'C'; }
/* pre.src-C++ doesn't work in CSS */
pre.src-clojure:before { content: 'Clojure'; }
pre.src-css:before { content: 'CSS'; }
pre.src-D:before { content: 'D'; }
pre.src-ditaa:before { content: 'ditaa'; }
pre.src-dot:before { content: 'Graphviz'; }
pre.src-calc:before { content: 'Emacs Calc'; }
pre.src-emacs-lisp:before { content: 'Emacs Lisp'; }
pre.src-fortran:before { content: 'Fortran'; }
pre.src-gnuplot:before { content: 'gnuplot'; }
pre.src-haskell:before { content: 'Haskell'; }
pre.src-hledger:before { content: 'hledger'; }
pre.src-java:before { content: 'Java'; }
pre.src-js:before { content: 'Javascript'; }
pre.src-latex:before { content: 'LaTeX'; }
pre.src-ledger:before { content: 'Ledger'; }
pre.src-lisp:before { content: 'Lisp'; }
pre.src-lilypond:before { content: 'Lilypond'; }
pre.src-lua:before { content: 'Lua'; }
pre.src-matlab:before { content: 'MATLAB'; }
pre.src-mscgen:before { content: 'Mscgen'; }
pre.src-ocaml:before { content: 'Objective Caml'; }
pre.src-octave:before { content: 'Octave'; }
pre.src-org:before { content: 'Org mode'; }
pre.src-oz:before { content: 'OZ'; }
pre.src-plantuml:before { content: 'Plantuml'; }
pre.src-processing:before { content: 'Processing.js'; }
pre.src-python:before { content: 'Python'; }
pre.src-R:before { content: 'R'; }
pre.src-ruby:before { content: 'Ruby'; }
pre.src-sass:before { content: 'Sass'; }
pre.src-scheme:before { content: 'Scheme'; }
pre.src-screen:before { content: 'Gnu Screen'; }
pre.src-sed:before { content: 'Sed'; }
pre.src-sh:before { content: 'shell'; }
pre.src-sql:before { content: 'SQL'; }
pre.src-sqlite:before { content: 'SQLite'; }
/* additional languages in org.el's org-babel-load-languages alist */
pre.src-forth:before { content: 'Forth'; }
pre.src-io:before { content: 'IO'; }
pre.src-J:before { content: 'J'; }
pre.src-makefile:before { content: 'Makefile'; }
pre.src-maxima:before { content: 'Maxima'; }
pre.src-perl:before { content: 'Perl'; }
pre.src-picolisp:before { content: 'Pico Lisp'; }
pre.src-scala:before { content: 'Scala'; }
pre.src-shell:before { content: 'Shell Script'; }
pre.src-ebnf2ps:before { content: 'ebfn2ps'; }
/* additional language identifiers per "defun org-babel-execute"
in ob-*.el */
pre.src-cpp:before { content: 'C++'; }
pre.src-abc:before { content: 'ABC'; }
pre.src-coq:before { content: 'Coq'; }
pre.src-groovy:before { content: 'Groovy'; }
/* additional language identifiers from org-babel-shell-names in
ob-shell.el: ob-shell is the only babel language using a lambda to put
the execution function name together. */
pre.src-bash:before { content: 'bash'; }
pre.src-csh:before { content: 'csh'; }
pre.src-ash:before { content: 'ash'; }
pre.src-dash:before { content: 'dash'; }
pre.src-ksh:before { content: 'ksh'; }
pre.src-mksh:before { content: 'mksh'; }
pre.src-posh:before { content: 'posh'; }
/* Additional Emacs modes also supported by the LaTeX listings package */
pre.src-ada:before { content: 'Ada'; }
pre.src-asm:before { content: 'Assembler'; }
pre.src-caml:before { content: 'Caml'; }
pre.src-delphi:before { content: 'Delphi'; }
pre.src-html:before { content: 'HTML'; }
pre.src-idl:before { content: 'IDL'; }
pre.src-mercury:before { content: 'Mercury'; }
pre.src-metapost:before { content: 'MetaPost'; }
pre.src-modula-2:before { content: 'Modula-2'; }
pre.src-pascal:before { content: 'Pascal'; }
pre.src-ps:before { content: 'PostScript'; }
pre.src-prolog:before { content: 'Prolog'; }
pre.src-simula:before { content: 'Simula'; }
pre.src-tcl:before { content: 'tcl'; }
pre.src-tex:before { content: 'TeX'; }
pre.src-plain-tex:before { content: 'Plain TeX'; }
pre.src-verilog:before { content: 'Verilog'; }
pre.src-vhdl:before { content: 'VHDL'; }
pre.src-xml:before { content: 'XML'; }
pre.src-nxml:before { content: 'XML'; }
/* add a generic configuration mode; LaTeX export needs an additional
(add-to-list 'org-latex-listings-langs '(conf " ")) in .emacs */
pre.src-conf:before { content: 'Configuration File'; }
table { border-collapse:collapse; }
caption.t-above { caption-side: top; }
caption.t-bottom { caption-side: bottom; }
td, th { vertical-align:top; }
th.org-right { text-align: center; }
th.org-left { text-align: center; }
th.org-center { text-align: center; }
td.org-right { text-align: right; }
td.org-left { text-align: left; }
td.org-center { text-align: center; }
dt { font-weight: bold; }
.footpara { display: inline; }
.footdef { margin-bottom: 1em; }
.figure { padding: 1em; }
.figure p { text-align: center; }
.equation-container {
display: table;
text-align: center;
width: 100%;
}
.equation {
vertical-align: middle;
}
.equation-label {
display: table-cell;
text-align: right;
vertical-align: middle;
}
.inlinetask {
padding: 10px;
border: 2px solid gray;
margin: 10px;
background: #ffffcc;
}
#org-div-home-and-up
{ text-align: right; font-size: 70%; white-space: nowrap; }
textarea { overflow-x: auto; }
.linenr { font-size: smaller }
.code-highlighted { background-color: #ffff00; }
.org-info-js_info-navigation { border-style: none; }
#org-info-js_console-label
{ font-size: 10px; font-weight: bold; white-space: nowrap; }
.org-info-js_search-highlight
{ background-color: #ffff00; color: #000000; font-weight: bold; }
.org-svg { }
</style>
<link rel="stylesheet" href="/assets/styles/style.css" />
<link rel="stylesheet" href="/assets/styles/bigger-picture.min.css" />
<link rel="stylesheet" href="/assets/styles/media.css" />
<script src="/assets/scripts/script.js" defer></script>
<script src="/assets/scripts/search.js" defer></script>
<script src="/assets/scripts/bigger-picture.min.js" defer></script>
<script src="/assets/scripts/svg-pan-zoom.min.js" defer></script>
<script src="/assets/scripts/gallery-init.js" defer></script>
<script>
window.MathJax = {
tex: {
ams: {
multlineWidth: '85%'
},
tags: 'ams',
tagSide: 'right',
tagIndent: '.8em'
},
chtml: {
scale: 1.0,
displayAlign: 'center',
displayIndent: '0em'
},
svg: {
scale: 1.0,
displayAlign: 'center',
displayIndent: '0em'
},
output: {
font: 'mathjax-modern',
displayOverflow: 'overflow'
}
};
</script>
<script
id="MathJax-script"
async
src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">
</script>
</head>
<body>
<div id="preamble" class="status">
<div class="banner-header">
<div class="banner-left">
<a href="/20241210233721-brain_moc.html"> <img src="/assets/gr.png" alt="Site Logo" class="banner-logo" /> </a>
<div id="updated">Updated: 2025-12-28 Sun 19:48</div>
</div>
<div class="banner-search">
<input id="search-box"
type="search"
placeholder="Search notes…"
aria-label="Search notes"
autocomplete="off" />
<div id="search-results"></div>
</div>
<button id="close-all">Close All</button>
</div>
</div>
<div id="stack-root">
<div class="stack-track">
<article class="stack-pane pane-root" data-url="/20250727221512-clean_code.html">
<div id="content" class="content">
<div class="title-section">
<div class="title-controls">
<button class="pane-fullscreen" aria-label="Fullscreen">F</button>
<button class="pane-edit" aria-label="Edit pane">E</button>
<button class="pane-close" aria-label="Close pane">×</button>
</div>
<h1 class="title">clean-code</h1>
<div class="title-metadata">
<span class="metadata-item">
<span class="metadata-label">planted:</span>
<span class="metadata-value">2025-07-27</span>
</span>
<span class="metadata-item">
<span class="metadata-label">last tended to:</span>
<span class="metadata-value">2025-12-28</span>
</span>
</div>
</div>
<div id="outline-container-org449317a" class="outline-2">
<h2 id="org449317a"><a href="#org449317a">Chapter 1: Clean Code</a></h2>
<div class="outline-text-2" id="text-org449317a">
<p>
Referenced Items:
</p>
<ul class="org-ul">
<li>Implementation Patterns, Kent Beck, Addison-Wesley, 2007.</li>
<li>Literate Programming, Donald E. Knuth, Center for the Study of Language and Information, Leland Stanford Junior University, 1992.</li>
</ul>
<p>
Principles mentioned:
Single Responsibility Principle (SRP), the Open Closed Principle (OCP), and the Dependency Inversion Principle (DIP)
</p>
</div>
</div>
<div id="outline-container-orgd786814" class="outline-2">
<h2 id="orgd786814"><a href="#orgd786814">Chapter 2: Meaningful Names</a></h2>
<div class="outline-text-2" id="text-orgd786814">
</div>
<div id="outline-container-org5d32a36" class="outline-3">
<h3 id="org5d32a36"><a href="#org5d32a36">Use intention revealing names:</a></h3>
<div class="outline-text-3" id="text-org5d32a36">
<p>
Names should reveal intent, there is no revelation in naming an integer <code>d</code>, intending it stands for days. Instead, you should use the following names:
</p>
<div class="org-src-container">
<pre class="src src-java">int elapsedTimeInDays;
int daysSinceCreation;
int daysSinceModification;
int fileAgeInDays;
</pre>
</div>
</div>
</div>
<div id="outline-container-org5240a9b" class="outline-3">
<h3 id="org5240a9b"><a href="#org5240a9b">Avoid disinformation</a></h3>
<div class="outline-text-3" id="text-org5240a9b">
<p>
Don&rsquo;t postfix the word &rsquo;list&rsquo; to the name &rsquo;accounts&rsquo; unless it&rsquo;s actually a list. This is because the reader will <i>assume</i> the data type of accountsList is indeed a list, instead choose a name like <code>accountsGroup</code>.
</p>
</div>
</div>
<div id="outline-container-org0a93489" class="outline-3">
<h3 id="org0a93489"><a href="#org0a93489">Make Meaningful Distinctions</a></h3>
<div class="outline-text-3" id="text-org0a93489">
<p>
While it is possible to name by being disinformative, it is also possible to name being non informative. Consider:
</p>
<div class="org-src-container">
<pre class="src src-java">
public static void copyChars(char a1[], char a2[]) {
for (int i = 0; i &lt; a1.length; i++) {
a2[i] = a1[i];
}
}
</pre>
</div>
<p>
What on earth does <code>a[1]</code> and <code>a[2]</code> even stand for? We are better off using names like source and destination (due to the function&rsquo;s intent of copying the array).
</p>
<p>
Furthermore, noise words are redundant. We should never use the word <code>variable</code> when naming a variable, or <code>table</code> when naming a table.
</p>
</div>
</div>
<div id="outline-container-org15c6c84" class="outline-3">
<h3 id="org15c6c84"><a href="#org15c6c84">Use Pronouncable Names</a></h3>
<div class="outline-text-3" id="text-org15c6c84">
<p>
This is quite straightforward. Do not use a name like <code>genymdhms</code> to refer to generation date, year, month, day, hour, minute,
and second. Instead use <code>generationTimeStamp</code>.
</p>
</div>
</div>
<div id="outline-container-orgdb2bfb4" class="outline-3">
<h3 id="orgdb2bfb4"><a href="#orgdb2bfb4">Use Searchable Names</a></h3>
<div class="outline-text-3" id="text-orgdb2bfb4">
<p>
In modern IDE&rsquo;s, it is still quite difficult to search for single-lettered variables. The writer states a personal preference of using single-letter names only as local variables and inside short methods. The following principle is given:
</p>
<p>
<i>The length of a name should correspond to the size of its scope</i>
</p>
</div>
</div>
<div id="outline-container-org0ef843b" class="outline-3">
<h3 id="org0ef843b"><a href="#org0ef843b">Avoid Encodings</a></h3>
<div class="outline-text-3" id="text-org0ef843b">
<p>
Don&rsquo;t prefix variables with letters like m_ as was done in the past. Do not type encode as well, an example of this is: <code>PhoneNumber phoneString;</code> we can see the reader being misled into thinking the phone number is a String.
</p>
</div>
</div>
<div id="outline-container-org66842fc" class="outline-3">
<h3 id="org66842fc"><a href="#org66842fc">Avoid Mental Mappings</a></h3>
<div class="outline-text-3" id="text-org66842fc">
<p>
Clarity is king, don&rsquo;t use a name for a variable that only you know what it stands for. For example: using the letter r as the lower-cased version of the url with the host and scheme
removed. That&rsquo;s being smart, not professional.
</p>
</div>
</div>
<div id="outline-container-org9dfc288" class="outline-3">
<h3 id="org9dfc288"><a href="#org9dfc288">Class Names</a></h3>
<div class="outline-text-3" id="text-org9dfc288">
<blockquote>
<p>
Classes and objects should have noun or noun phrase names like Customer, WikiPage,
Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info in the name
of a class. A class name should not be a verb.
</p>
</blockquote>
<p>
<blockquote class="epigraph"><p>Classes and objects should have noun or noun phrase names like Customer, WikiPage, Account, and AddressParser. Avoid words like Manager, Processor, Data, or Info in the name of a class. A class name should not be a verb</p><footer></footer></blockquote>
</p>
</div>
</div>
<div id="outline-container-org5aface4" class="outline-3">
<h3 id="org5aface4"><a href="#org5aface4">Method Names</a></h3>
<div class="outline-text-3" id="text-org5aface4">
<p>
Methods should have verb or verb phrase names.
</p>
</div>
</div>
<div id="outline-container-org386a876" class="outline-3">
<h3 id="org386a876"><a href="#org386a876">Don&rsquo;t be cute/Don&rsquo;t use puns</a></h3>
<div class="outline-text-3" id="text-org386a876">
<p>
Do not use names that are only understandable to people whom you share jokes etc with. Furthermore, do not use colloquialism and slang in names.
</p>
<ul class="org-ul">
<li>Example: <code>HandGrenade</code> instead of <code>DeleteItems</code></li>
<li>Example: <code>whack()</code> instead of <code>kill()</code></li>
</ul>
</div>
</div>
<div id="outline-container-org8191419" class="outline-3">
<h3 id="org8191419"><a href="#org8191419">Pick one word per concept</a></h3>
<div class="outline-text-3" id="text-org8191419">
<p>
If you have multiple choices for naming a concept, use one and stick with it. For instance if your options are fetch, get and retrieve, use one and stick with it throughout.
</p>
</div>
</div>
<div id="outline-container-org283e711" class="outline-3">
<h3 id="org283e711"><a href="#org283e711">Solution Domain Names and Problem Domain Names</a></h3>
<div class="outline-text-3" id="text-org283e711">
<p>
Where possible use solution domain names, as the people that are going to be reading the code are programmers. Therefore, do not shy away from using CS terms, algorithm names, math names and so forth.
</p>
<p>
However when it is not possible to use solution domain names (in other words, when there is no &ldquo;programmer-eese&rdquo; then use the name from the problem domain. The other programmers can ask the domain expert for clarification. If the code is more to do with the problem domain concepts, then the names should be drawn from them.
</p>
</div>
</div>
<div id="outline-container-orgde08904" class="outline-3">
<h3 id="orgde08904"><a href="#orgde08904">Add Meaningful Context</a></h3>
<div class="outline-text-3" id="text-orgde08904">
<p>
Enclose names with well-named classes, functions, or namespaces. When all else fails, then prefix with something that provides more context.
</p>
</div>
</div>
<div id="outline-container-org851c073" class="outline-3">
<h3 id="org851c073"><a href="#org851c073">Don&rsquo;t add gratuitous context</a></h3>
<div class="outline-text-3" id="text-org851c073">
<p>
Shorter names are better than longer ones, generally. This is so long as the context and intent is clear. Don&rsquo;t add redundant or irrelevant additions to the name in the for the sake of &rsquo;context&rsquo;.
</p>
</div>
</div>
</div>
<div id="outline-container-org4b2e6df" class="outline-2">
<h2 id="org4b2e6df"><a href="#org4b2e6df">Chapter 3: Functions</a></h2>
<div class="outline-text-2" id="text-org4b2e6df">
</div>
<div id="outline-container-orgc9f1000" class="outline-3">
<h3 id="orgc9f1000"><a href="#orgc9f1000">Functions should be small</a></h3>
<div class="outline-text-3" id="text-orgc9f1000">
<p>
Functions should be extremely short—ideally just a few lines, so they remain easy to understand and maintain.
</p>
<p>
Avoid deeply nested blocks; keep indentation shallow (12 levels), often replacing blocks with descriptive function calls.
</p>
<p>
A small function tells a concise, self-contained story, making it easier for readers to follow the programs intent.
</p>
<p>
The smaller the function, the more descriptive and accurate its name can be, improving self-documentation.
</p>
<p>
Large functions hide complexity and mix abstraction levels, making errors and duplication more likely.
</p>
</div>
</div>
<div id="outline-container-org5021117" class="outline-3">
<h3 id="org5021117"><a href="#org5021117">Do One Thing &amp; One Level of Abstraction</a></h3>
<div class="outline-text-3" id="text-org5021117">
<p>
A function should do exactly one conceptual task, and all its statements should exist at the same abstraction level.
</p>
<p>
Mixing details (like string concatenation) with high-level actions (like rendering a page) causes confusion.
</p>
<p>
The Stepdown Rule: organise functions so they read like a top down narrative, each calling the next abstraction level.
</p>
<p>
If you can extract a subfunction with a name that isnt a restatement, the original function is doing too much.
</p>
<p>
Functions that “do one thing” cannot be logically split into sections such as “initialize,” “process,” “finalize.”
</p>
</div>
</div>
<div id="outline-container-orgff7f821" class="outline-3">
<h3 id="orgff7f821"><a href="#orgff7f821">Switch Statements</a></h3>
<div class="outline-text-3" id="text-orgff7f821">
<p>
Switch statements naturally violate “do one thing” by handling multiple cases; they also grow in size over time.
</p>
<p>
They break the Single Responsibility Principle (multiple reasons to change) and Open-Closed Principle (must change for new cases).
</p>
<p>
Preferred approach: hide switch statements inside a factory and dispatch behavior polymorphically through an interface.
</p>
<p>
Allow only one visible switch in your system, used solely for object creation, then encapsulate it.
</p>
<p>
This removes duplication and keeps high-level code unaware of concrete type distinctions.
</p>
<p>
Example:
</p>
<div class="org-src-container">
<pre class="src src-java">public abstract class Employee {
public abstract boolean isPayday();
public abstract Money calculatePay();
public abstract void deliverPay(Money pay);
}
-----------------
public interface EmployeeFactory {
public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType;
}
-----------------
public class EmployeeFactoryImpl implements EmployeeFactory {
public Employee makeEmployee(EmployeeRecord r) throws InvalidEmployeeType {
switch (r.type) {
case COMMISSIONED:
return new CommissionedEmployee(r) ;
case HOURLY:
return new HourlyEmployee(r);
case SALARIED:
return new SalariedEmploye(r);
default:
throw new InvalidEmployeeType(r.type);
}
}
}
</pre>
</div>
</div>
</div>
<div id="outline-container-org78eba20" class="outline-3">
<h3 id="org78eba20"><a href="#org78eba20">Use Descriptive Names</a></h3>
<div class="outline-text-3" id="text-org78eba20">
<p>
A functions name should clearly state its purpose. Long, descriptive names beat short, cryptic ones.
</p>
<p>
Consistent naming patterns (shared verbs/nouns) help code read like a coherent story and aid predictability.
</p>
<p>
Descriptive names reduce the need for comments and improve comprehension without external documentation.
</p>
<p>
Renaming functions can reveal design improvements, so try multiple options until the best emerges.
</p>
<p>
IDE refactoring tools make renaming safe, encouraging experimentation.
</p>
</div>
</div>
<div id="outline-container-org3591ab5" class="outline-3">
<h3 id="org3591ab5"><a href="#org3591ab5">Function Arguments</a></h3>
<div class="outline-text-3" id="text-org3591ab5">
<p>
<blockquote class="epigraph"><p>The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldnt be used anyway.</p><footer></footer></blockquote>
</p>
<p>
Fewer arguments = better; aim for 02, avoid more than 3 unless absolutely necessary.
</p>
<p>
Flag arguments (booleans) are a red flag—they imply the function does multiple things.
</p>
<p>
Group related parameters into objects (e.g., <code>Point</code> for <code>x</code> and <code>y</code>) to reduce argument count and improve clarity.
</p>
<p>
Output arguments are confusing—prefer returning values or mutating the owning objects state.
</p>
<p>
Match function/argument names in verbnoun or keyword style (e.g., <code>writeField(name)</code>, <code>assertExpectedEqualsActual</code>).
</p>
</div>
</div>
<div id="outline-container-org364d29d" class="outline-3">
<h3 id="org364d29d"><a href="#org364d29d">Have No Side Effects</a></h3>
<div class="outline-text-3" id="text-org364d29d">
<p>
A function should do only what its name promises. Hidden state changes are misleading and dangerous.
</p>
<p>
Side effects create temporal coupling, meaning the function must be called in a certain sequence to be safe.
</p>
<p>
If unavoidable, make side effects explicit in the name (e.g., <code>checkPasswordAndInitializeSession</code>).
</p>
<p>
Clear separation of command and query functions avoids ambiguity in meaning and intent.
</p>
<p>
Functions that modify state and return information often cause confusion and should be split.
</p>
</div>
</div>
<div id="outline-container-org44a7561" class="outline-3">
<h3 id="org44a7561"><a href="#org44a7561">Error Handling</a></h3>
<div class="outline-text-3" id="text-org44a7561">
<p>
Error handling is a single responsibility—separate it from normal logic to keep both paths clear.
</p>
<p>
Prefer exceptions over error codes to avoid cluttering the happy path and to reduce dependency magnets.
</p>
<p>
Extract try/catch bodies into their own functions for cleaner structure.
</p>
<p>
See below:
</p>
<div class="org-src-container">
<pre class="src src-java">
public void delete(Page page) {
try {
deletePageAndAllReferences(page);
}
catch (Exception e) {
logError(e);
}
}
private void deletePageAndAllReferences(Page page) throws Exception {
deletePage(page);
registry.deleteReference(page.name);
configKeys.deleteKey(page.name.makeKey());
}
private void logError(Exception e) {
logger.log(e.getMessage());
}
</pre>
</div>
<p>
Keep functions small enough that occasional multiple return or break statements are acceptable.
</p>
<p>
Avoid duplication in error handling, and follow the DRY principle to ensure changes occur in one place.
</p>
</div>
</div>
</div>
<div id="outline-container-orgf070646" class="outline-2">
<h2 id="orgf070646"><a href="#orgf070646">Chapter 4: Comments</a></h2>
<div class="outline-text-2" id="text-orgf070646">
<p>
Comments are a necessary evil—they exist because code fails to express intent clearly.
</p>
<p>
Outdated comments are dangerous; they can mislead more than help.
</p>
<p>
Strive to write code that explains itself; comments should be minimized.
</p>
<p>
Truth is always in the code, not in the comments.
</p>
</div>
<div id="outline-container-org625414f" class="outline-3">
<h3 id="org625414f"><a href="#org625414f">Comments Do Not Make Up for Bad Code</a></h3>
<div class="outline-text-3" id="text-org625414f">
<p>
Dont use comments to excuse messy, unclear code—clean the code instead.
</p>
<p>
Clear, expressive code with few comments &gt; cluttered code with many comments.
</p>
<div class="org-src-container">
<pre class="src src-java">
// Check to see if the employee is eligible for full benefits
if ((employee.flags &amp; HOURLY_FLAG) &amp;&amp; (employee.age &gt; 65))
// Better:
if (employee.isEligibleForFullBenefits())
</pre>
</div>
</div>
</div>
<div id="outline-container-orgd7b01d4" class="outline-3">
<h3 id="orgd7b01d4"><a href="#orgd7b01d4">Good Comments</a></h3>
<div class="outline-text-3" id="text-orgd7b01d4">
<p>
Only write them when unavoidable.
</p>
</div>
</div>
<div id="outline-container-org362c758" class="outline-3">
<h3 id="org362c758"><a href="#org362c758">Legal Comments</a></h3>
<div class="outline-text-3" id="text-org362c758">
<p>
Sometimes required for copyright/licensing.
</p>
<p>
Keep them short; refer to standard licenses rather than embedding full legal text.
</p>
</div>
</div>
<div id="outline-container-org01a861f" class="outline-3">
<h3 id="org01a861f"><a href="#org01a861f">Informative Comments</a></h3>
<div class="outline-text-3" id="text-org01a861f">
<p>
Explain return values, formats, or patterns.
</p>
<p>
Prefer naming/structuring code to make such comments unnecessary.
</p>
<div class="org-src-container">
<pre class="src src-java">
// format matched kk:mm:ss EEE, MMM dd, yyyy
Pattern timeMatcher = Pattern.compile("\\d*:\\d*:\\d* \\w*, \\w* \\d*, \\d*");
</pre>
</div>
</div>
</div>
<div id="outline-container-org103a8e1" class="outline-3">
<h3 id="org103a8e1"><a href="#org103a8e1">Explanation of Intent</a></h3>
<div class="outline-text-3" id="text-org103a8e1">
<p>
Describe why a certain approach was chosen.
</p>
<p>
Helps future maintainers understand reasoning behind code.
</p>
<p>
return 1; // we are greater because we are the right type.
</p>
</div>
</div>
<div id="outline-container-org2dd2263" class="outline-3">
<h3 id="org2dd2263"><a href="#org2dd2263">Clarification</a></h3>
<div class="outline-text-3" id="text-org2dd2263">
<p>
Translate obscure values into readable terms.
</p>
<p>
Useful when working with unchangeable APIs/libraries, but risky if incorrect.
</p>
</div>
</div>
<div id="outline-container-orgc20f483" class="outline-3">
<h3 id="orgc20f483"><a href="#orgc20f483">Warning of Consequences</a></h3>
<div class="outline-text-3" id="text-orgc20f483">
<p>
Alert others about performance, thread-safety, or side effects.
</p>
<p>
// SimpleDateFormat is not thread safe, so create each instance independently.
</p>
</div>
</div>
<div id="outline-container-org466f772" class="outline-3">
<h3 id="org466f772"><a href="#org466f772">\TODO\ Comments</a></h3>
<div class="outline-text-3" id="text-org466f772">
<p>
Mark incomplete work or planned improvements.
</p>
<p>
Should be reviewed regularly; not an excuse for bad code.
</p>
</div>
</div>
<div id="outline-container-org6d9f834" class="outline-3">
<h3 id="org6d9f834"><a href="#org6d9f834">Amplification</a></h3>
<div class="outline-text-3" id="text-org6d9f834">
<p>
Highlight the importance of seemingly small details.
</p>
<p>
// the trim is real important. It removes starting spaces&#x2026;
</p>
</div>
</div>
<div id="outline-container-org7bf8e6d" class="outline-3">
<h3 id="org7bf8e6d"><a href="#org7bf8e6d">Javadocs in Public APIs</a></h3>
<div class="outline-text-3" id="text-org7bf8e6d">
<p>
Public APIs should have clear documentation.
</p>
<p>
Javadocs can also mislead—keep them accurate and up-to-date.
</p>
</div>
</div>
<div id="outline-container-orgfcb9b90" class="outline-3">
<h3 id="orgfcb9b90"><a href="#orgfcb9b90">Dont Use a Comment When You Can Use a Function or Variable</a></h3>
<div class="outline-text-3" id="text-orgfcb9b90">
<p>
Replace explanatory comments with expressive variable or function names.
</p>
<p>
Refactor code to remove comment redundancy.
</p>
</div>
</div>
<div id="outline-container-org5c32b00" class="outline-3">
<h3 id="org5c32b00"><a href="#org5c32b00">Position Markers</a></h3>
<div class="outline-text-3" id="text-org5c32b00">
<p>
Avoid decorative banners like // Actions ///////////////////////—they add clutter.
</p>
<p>
Use sparingly and only for meaningful grouping.
</p>
<p>
Overuse makes them blend into background noise.
</p>
</div>
</div>
<div id="outline-container-orgd425399" class="outline-3">
<h3 id="orgd425399"><a href="#orgd425399">Closing Brace Comments</a></h3>
<div class="outline-text-3" id="text-orgd425399">
<p>
Comments on closing braces (} // while) are unnecessary for small, well-structured functions.
</p>
<p>
Prefer short, clear functions over brace markers.
</p>
</div>
</div>
<div id="outline-container-orgf689aca" class="outline-3">
<h3 id="orgf689aca"><a href="#orgf689aca">Attributions and Bylines</a></h3>
<div class="outline-text-3" id="text-orgf689aca">
<p>
Dont add personal tags like /* Added by Rick */—use version control for authorship history.
</p>
<p>
Such comments become outdated and irrelevant over time.
</p>
</div>
</div>
<div id="outline-container-orgcf0035e" class="outline-3">
<h3 id="orgcf0035e"><a href="#orgcf0035e">Commented-Out Code</a></h3>
<div class="outline-text-3" id="text-orgcf0035e">
<p>
Never keep old code commented out; delete it and rely on version control history.
</p>
<p>
Commented-out code adds clutter and confuses future maintainers.
</p>
<div class="org-src-container">
<pre class="src src-java">
// Old cruft that should be deleted:
//hdrPos = bytePos;
//dataPos = bytePos;
</pre>
</div>
</div>
</div>
<div id="outline-container-org1db2ac4" class="outline-3">
<h3 id="org1db2ac4"><a href="#org1db2ac4">HTML Comments</a></h3>
<div class="outline-text-3" id="text-org1db2ac4">
<p>
Avoid HTML markup inside code comments—it makes them harder to read in the editor.
</p>
<p>
Let documentation tools (like Javadoc) handle formatting.
</p>
</div>
</div>
<div id="outline-container-org8b17ee8" class="outline-3">
<h3 id="org8b17ee8"><a href="#org8b17ee8">Nonlocal Information</a></h3>
<div class="outline-text-3" id="text-org8b17ee8">
<p>
Comments should describe nearby code only, not unrelated parts of the system.
</p>
<p>
Avoid embedding global/system details that the function cant control.
</p>
</div>
</div>
<div id="outline-container-org12390d8" class="outline-3">
<h3 id="org12390d8"><a href="#org12390d8">Too Much Information</a></h3>
<div class="outline-text-3" id="text-org12390d8">
<p>
Avoid long, unnecessary historical or technical explanations.
</p>
<p>
Keep only relevant context (e.g., “RFC 2045” reference is fine, not the full spec).
</p>
</div>
</div>
<div id="outline-container-org45444dc" class="outline-3">
<h3 id="org45444dc"><a href="#org45444dc">Inobvious Connection</a></h3>
<div class="outline-text-3" id="text-org45444dc">
<p>
Ensure the relationship between comment and code is clear.
</p>
<p>
Dont make readers guess what part of the code the comment refers to.
</p>
<div class="org-src-container">
<pre class="src src-java">
// plus filter bytes ... but which part is “filter”?
this.pngBytes = new byte[((this.width + 1) * this.height * 3) + 200];
</pre>
</div>
</div>
</div>
<div id="outline-container-org2141cad" class="outline-3">
<h3 id="org2141cad"><a href="#org2141cad">Function Headers</a></h3>
<div class="outline-text-3" id="text-org2141cad">
<p>
Short, single-purpose functions with good names dont need header comments.
</p>
<p>
Let the function name explain the purpose.
</p>
</div>
</div>
<div id="outline-container-org906ec96" class="outline-3">
<h3 id="org906ec96"><a href="#org906ec96">Javadocs in Nonpublic Code</a></h3>
<div class="outline-text-3" id="text-org906ec96">
<p>
Javadocs are useful for public APIs, but excessive formality in internal code is just noise.
</p>
<p>
Internal methods should be self-explanatory without full doc comments.
</p>
</div>
</div>
<div id="outline-container-org3765d71" class="outline-3">
<h3 id="org3765d71"><a href="#org3765d71">Example: Refactored Prime Generator</a></h3>
<div class="outline-text-3" id="text-org3765d71">
<p>
Original code: Over-commented, with redundant explanations and irrelevant history.
</p>
<p>
Refactored version: Only two comments remain—both explain why, not what.
</p>
<p>
One eases the reader into the algorithm.
</p>
<p>
One explains rationale for using the square root as a loop limit.
</p>
</div>
</div>
</div>
<div id="outline-container-org77b408e" class="outline-2">
<h2 id="org77b408e"><a href="#org77b408e">Chapter 5: Formatting</a></h2>
<div class="outline-text-2" id="text-org77b408e">
</div>
<div id="outline-container-org36f1142" class="outline-3">
<h3 id="org36f1142"><a href="#org36f1142">Vertical Formatting (Clean Code, Ch.5)</a></h3>
<div class="outline-text-3" id="text-org36f1142">
</div>
<div id="outline-container-org850e1db" class="outline-4">
<h4 id="org850e1db"><a href="#org850e1db">Vertical Formatting</a></h4>
<div class="outline-text-4" id="text-org850e1db">
<ul class="org-ul">
<li>Vertical openness (blank lines) separates concepts and improves readability.</li>
<li>Too much density makes code look like a muddle and harder to scan.</li>
</ul>
</div>
</div>
<div id="outline-container-org640f586" class="outline-4">
<h4 id="org640f586"><a href="#org640f586">Vertical Density</a></h4>
<div class="outline-text-4" id="text-org640f586">
<ul class="org-ul">
<li>Tightly related lines should appear vertically dense.</li>
<li>Avoid useless comments that interrupt association.</li>
<li>Example (bad):</li>
</ul>
<div class="org-src-container">
<pre class="src src-java">public class ReporterConfig {
/**
* The class name of the reporter listener
*/
private String m_className;
</pre>
</div>
<ul class="org-ul">
<li>Example (better):</li>
</ul>
<div class="org-src-container">
<pre class="src src-java">public class ReporterConfig {
private String m_className;
private List&lt;Property&gt; m_properties = new ArrayList&lt;&gt;();
</pre>
</div>
</div>
</div>
<div id="outline-container-org69376bc" class="outline-4">
<h4 id="org69376bc"><a href="#org69376bc">Vertical Distance</a></h4>
<div class="outline-text-4" id="text-org69376bc">
<ul class="org-ul">
<li>Related concepts should be kept close together to reduce scrolling and searching.</li>
<li>Local variables → as close to use as possible, usually at top of function.</li>
<li>Control variables → declared inside loop headers.</li>
<li>Instance variables → declared at the top of class (common Java convention).</li>
</ul>
<div class="org-src-container">
<pre class="src src-java">for (Test each : tests) {
count += each.countTestCases();
}
</pre>
</div>
<ul class="org-ul">
<li>Dependent functions: caller above callee for natural top-down reading.</li>
</ul>
<div class="org-src-container">
<pre class="src src-java">public Response makeResponse(...) {
String pageName = getPageNameOrDefault(request, "FrontPage");
loadPage(pageName, context);
return makePageResponse(context);
}
private String getPageNameOrDefault(Request request, String defaultPageName) { ... }
</pre>
</div>
</div>
</div>
<div id="outline-container-org9a98ae3" class="outline-4">
<h4 id="org9a98ae3"><a href="#org9a98ae3">Conceptual Affinity</a></h4>
<div class="outline-text-4" id="text-org9a98ae3">
<ul class="org-ul">
<li>Group functions with similar naming or shared purpose.</li>
<li>Example (JUnit assert methods):</li>
</ul>
<div class="org-src-container">
<pre class="src src-java">static public void assertTrue(String message, boolean condition) { ... }
static public void assertTrue(boolean condition) { ... }
static public void assertFalse(String message, boolean condition) { ... }
static public void assertFalse(boolean condition) { ... }
</pre>
</div>
</div>
</div>
<div id="outline-container-org220afb9" class="outline-4">
<h4 id="org220afb9"><a href="#org220afb9">Vertical Ordering</a></h4>
<div class="outline-text-4" id="text-org220afb9">
<ul class="org-ul">
<li>Organise code top down:
<ul class="org-ul">
<li>High-level concepts first (main logic).</li>
<li>Lower-level details later.</li>
</ul></li>
<li>Readers can skim like a newspaper: important first, details last.</li>
<li>Contrast: C/C++ require declarations before use, Java does not.</li>
</ul>
</div>
</div>
<div id="outline-container-org07e9e3f" class="outline-4">
<h4 id="org07e9e3f"><a href="#org07e9e3f">Summary - vertical</a></h4>
<div class="outline-text-4" id="text-org07e9e3f">
<ul class="org-ul">
<li>Use vertical openness to separate concepts.</li>
<li>Use vertical density to group related ones.</li>
<li>Keep related variables, methods, and concepts close together.</li>
<li>Order code top down for natural readability.</li>
</ul>
</div>
</div>
</div>
<div id="outline-container-org4cee156" class="outline-3">
<h3 id="org4cee156"><a href="#org4cee156">Horizontal Formatting</a></h3>
<div class="outline-text-3" id="text-org4cee156">
<p>
Keep lines short — most professional code naturally stays within ~45 characters, with ~80 as an upper bound. Lines beyond 100120 characters are generally careless.
</p>
<p>
Avoid shrinking font or overly wide monitors to fit more code — readability &gt; fitting more characters.
</p>
<p>
Example limit guideline:
</p>
<div class="org-src-container">
<pre class="src src-java">// Good (short)
int sum = a + b + c;
// Bad (too long)
int sum = a + b + c + d + e + f + g + h + i + j + k + l + m + n + o + p + q;
</pre>
</div>
</div>
</div>
<div id="outline-container-orgbfb9dbd" class="outline-3">
<h3 id="orgbfb9dbd"><a href="#orgbfb9dbd">Horizontal Openness and Density</a></h3>
<div class="outline-text-3" id="text-orgbfb9dbd">
<p>
Use spaces to separate low-precedence operators (e.g., +, -, =) and improve readability.
</p>
<p>
Do not put spaces between function names and parentheses — they are closely related.
</p>
<p>
Example (Quadratic formula formatting):
</p>
<div class="org-src-container">
<pre class="src src-java">return (-b + Math.sqrt(determinant)) / (2*a);
</pre>
</div>
<p>
Separate arguments with spaces after commas to show distinct parameters.
</p>
</div>
</div>
<div id="outline-container-org62636bd" class="outline-3">
<h3 id="org62636bd"><a href="#org62636bd">Horizontal Alignment</a></h3>
<div class="outline-text-3" id="text-org62636bd">
<p>
Avoid aligning variable declarations or assignments in columns — it draws the eye to the wrong place.
</p>
<p>
Long aligned lists usually mean the class is too large and should be split.
</p>
<p>
Example (preferred unaligned):
</p>
<div class="org-src-container">
<pre class="src src-java"> // Prefer this:
private Socket socket;
private InputStream input;
private OutputStream output;
//instead of:
private Socket socket;
private InputStream input;
private OutputStream output;
</pre>
</div>
</div>
</div>
<div id="outline-container-org405763b" class="outline-3">
<h3 id="org405763b"><a href="#org405763b">Indentation</a></h3>
<div class="outline-text-3" id="text-org405763b">
<p>
Indent according to scope hierarchy:
</p>
<p>
Classes → no indent
</p>
<p>
Methods → 1 level
</p>
<p>
Method bodies → 2 levels
</p>
<p>
Inner blocks → +1 for each nesting
</p>
<p>
Indentation makes scopes visually obvious; without it, code is hard to scan.
</p>
<p>
Avoid collapsing scopes onto one line — always use braces and proper indenting.
</p>
</div>
</div>
<div id="outline-container-orgc320766" class="outline-3">
<h3 id="orgc320766"><a href="#orgc320766">Dummy Scopes</a></h3>
<div class="outline-text-3" id="text-orgc320766">
<p>
Avoid dummy bodies in loops (e.g., empty while or for loops).
</p>
<p>
If unavoidable, place semicolon on its own indented line to make it visible.
</p>
<div class="org-src-container">
<pre class="src src-java">while (dis.read(buf, 0, size) != -1)
;
</pre>
</div>
</div>
</div>
<div id="outline-container-org0a3881b" class="outline-3">
<h3 id="org0a3881b"><a href="#org0a3881b">Team Rules</a></h3>
<div class="outline-text-3" id="text-org0a3881b">
<p>
Teams must agree on a single formatting style for consistency.
</p>
<p>
Use IDE formatters to enforce these rules across all files.
</p>
<p>
Consistent formatting builds trust and reduces mental load for readers.
</p>
</div>
</div>
<div id="outline-container-orgce4a26e" class="outline-3">
<h3 id="orgce4a26e"><a href="#orgce4a26e">Uncle Bobs Formatting Rules (Example in CodeAnalyzer.java)</a></h3>
<div class="outline-text-3" id="text-orgce4a26e">
<p>
Short, clear methods with consistent spacing and indentation.
</p>
<p>
Use spaces around assignment and low-precedence operators, no space for high-precedence operators.
</p>
<p>
Avoid deeply nested structures — prefer clear, flat logic.
</p>
<p>
Example snippet:
</p>
<div class="org-src-container">
<pre class="src src-java">private void measureLine(String line) {
lineCount++;
int lineSize = line.length();
totalChars += lineSize;
lineWidthHistogram.addLine(lineSize, lineCount);
recordWidestLine(lineSize);
}
</pre>
</div>
</div>
</div>
</div>
<div id="outline-container-orged90cdd" class="outline-2">
<h2 id="orged90cdd"><a href="#orged90cdd">Chapter 6: Objects and Data Structures</a></h2>
</div>
<div id="outline-container-orgb6e26d6" class="outline-2">
<h2 id="orgb6e26d6"><a href="#orgb6e26d6">Chapter 7: Error Handling</a></h2>
</div>
<div id="outline-container-org903590c" class="outline-2">
<h2 id="org903590c"><a href="#org903590c">Chapter 8: Boundaries</a></h2>
</div>
<div id="outline-container-org15c6984" class="outline-2">
<h2 id="org15c6984"><a href="#org15c6984">Chapter 9: Unit Tests</a></h2>
</div>
<div id="outline-container-orgef3be3a" class="outline-2">
<h2 id="orgef3be3a"><a href="#orgef3be3a">Chapter 10: Classes</a></h2>
</div>
<div id="outline-container-orga9337d2" class="outline-2">
<h2 id="orga9337d2"><a href="#orga9337d2">Chapter 11: Systems</a></h2>
</div>
<div id="outline-container-org2c27910" class="outline-2">
<h2 id="org2c27910"><a href="#org2c27910">Chapter 12: Emergence</a></h2>
</div>
<div id="outline-container-org96fc104" class="outline-2">
<h2 id="org96fc104"><a href="#org96fc104">Chapter 13: Concurrency</a></h2>
</div>
<div id="outline-container-orgf9510a7" class="outline-2">
<h2 id="orgf9510a7"><a href="#orgf9510a7">Chapter 14: Successive Refinement</a></h2>
</div>
<div id="outline-container-org9131210" class="outline-2">
<h2 id="org9131210"><a href="#org9131210">Chapter 15: JUnit Internals</a></h2>
</div>
<div id="outline-container-org345aa69" class="outline-2">
<h2 id="org345aa69"><a href="#org345aa69">Chapter 16: Refactoring SerialDate</a></h2>
</div>
<div id="outline-container-org0617b06" class="outline-2">
<h2 id="org0617b06"><a href="#org0617b06">Chapter 17: Smells and Heuristics</a></h2>
</div>
<div id="outline-container-org5e01642" class="outline-2">
<h2 id="org5e01642"><a href="#org5e01642">Apendix A: Concurrency II</a></h2>
<div class="outline-text-2" id="text-org5e01642">
<p class="backlinks-section" id="backlinks">
Backlinks
</p>
<ul class="org-ul backlinks-list">
<li><a href="20241231172511-book_notes.html#ID-2706598f-e6aa-4e88-8d24-5f699bd22787">book<sub>notes</sub></a></li>
</ul>
</div>
</div>
</div>
</div></article></div></div>
<div id="postamble" class="status">
<footer>
<div class="copyright-container">
<div class="copyright">
Copyright &copy; 2022-2025 Zaine Qayyum. All rights reserved unless otherwise noted.</div></div>
<div class="generated">
Created with <a href="https://www.gnu.org/software/emacs/">Emacs</a> 30.2 (<a href="https://orgmode.org">Org</a> mode 9.7.11) on <a href="https://www.archlinux.org/">Arch</a> <a href="https://www.gnu.org">GNU</a>/<a href="https://www.kernel.org/">Linux</a>
</div>
</footer>
</div>
</body>
</html>