mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
Every page now loads /webmcp.js, scripts/webmcp.ts with its types stripped (npm run webmcp). Where the browser has document.modelContext it registers two read-only tools: search_skills over the published skills index, and get_skill, which returns a skill's markdown checked against the index digest. The markdown alternate link moves from build.py to site.py, so CI holds every page to it. The API catalog gains the site itself (llms.txt and the skills index) and hanzo.ai/agents; the live discovery check now fetches every catalog link. tests/site.mjs drives the tools through a recording modelContext, and checks a browser without one loads clean.
768 lines
30 KiB
HTML
768 lines
30 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>engineering-code-quality</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/engineering-code-quality">
|
|
<link rel="alternate" type="text/markdown" href="/engineering-code-quality.md">
|
|
<script type="module" src="/webmcp.js"></script>
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/engineering-code-quality.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>engineering-code-quality</h1><p class="lede">Code quality metrics, maintainability principles, SOLID design, code smells detection, and quality measurement</p><h1>Code Quality & Maintainability</h1>
|
|
<p><strong>Scope</strong>: Comprehensive guide to code quality principles, SOLID design, code smells, metrics, and long-term maintainability <strong>Lines</strong>: ~400 <strong>Last Updated</strong>: 2025-10-27 <strong>Format Version</strong>: 1.0 (Atomic)</p>
|
|
<hr>
|
|
<h2>When to Use This Skill</h2>
|
|
<p>Activate this skill when:</p>
|
|
<ul><li>Evaluating code quality in reviews or audits</li><li>Establishing quality standards for a team</li><li>Refactoring legacy code to improve maintainability</li><li>Setting up code quality metrics and monitoring</li><li>Training engineers on clean code principles</li><li>Defining "done" criteria for features</li><li>Improving codebase health over time</li><li>Reducing bug rates and technical debt</li></ul>
|
|
<h2>Core Concepts</h2>
|
|
<h3>Concept 1: The SOLID Principles</h3>
|
|
<p><strong>S - Single Responsibility Principle</strong></p>
|
|
<blockquote><p>A class/function should have one reason to change</p></blockquote>
|
|
<pre><code class="lang-python"># Bad: User class does too much
|
|
class User:
|
|
def save_to_database(self): ...
|
|
def send_email(self): ...
|
|
def generate_pdf_report(self): ...
|
|
def validate_password(self): ...
|
|
|
|
# Good: Each class has one responsibility
|
|
class User:
|
|
def validate_password(self): ...
|
|
|
|
class UserRepository:
|
|
def save(self, user: User): ...
|
|
|
|
class EmailService:
|
|
def send_welcome_email(self, user: User): ...
|
|
|
|
class ReportGenerator:
|
|
def generate_user_report(self, user: User): ...</code></pre>
|
|
<p><strong>O - Open/Closed Principle</strong></p>
|
|
<blockquote><p>Open for extension, closed for modification</p></blockquote>
|
|
<pre><code class="lang-python"># Bad: Must modify class to add new payment method
|
|
class PaymentProcessor:
|
|
def process(self, method: str, amount: float):
|
|
if method == "credit_card":
|
|
# Credit card logic
|
|
elif method == "paypal":
|
|
# PayPal logic
|
|
elif method == "bitcoin": # Must modify existing code!
|
|
# Bitcoin logic
|
|
|
|
# Good: Extend via new classes
|
|
class PaymentMethod:
|
|
def process(self, amount: float): ...
|
|
|
|
class CreditCardPayment(PaymentMethod):
|
|
def process(self, amount: float): ...
|
|
|
|
class PayPalPayment(PaymentMethod):
|
|
def process(self, amount: float): ...
|
|
|
|
class PaymentProcessor:
|
|
def process(self, method: PaymentMethod, amount: float):
|
|
method.process(amount) # No modification needed!</code></pre>
|
|
<p><strong>L - Liskov Substitution Principle</strong></p>
|
|
<blockquote><p>Subtypes must be substitutable for their base types</p></blockquote>
|
|
<pre><code class="lang-typescript">// Bad: Violates LSP
|
|
class Rectangle {
|
|
width: number;
|
|
height: number;
|
|
setWidth(w: number) { this.width = w; }
|
|
setHeight(h: number) { this.height = h; }
|
|
area(): number { return this.width * this.height; }
|
|
}
|
|
|
|
class Square extends Rectangle {
|
|
setWidth(w: number) {
|
|
this.width = w;
|
|
this.height = w; // Breaks expected Rectangle behavior!
|
|
}
|
|
}
|
|
|
|
// Good: Composition over inheritance
|
|
interface Shape {
|
|
area(): number;
|
|
}
|
|
|
|
class Rectangle implements Shape {
|
|
constructor(private width: number, private height: number) {}
|
|
area(): number { return this.width * this.height; }
|
|
}
|
|
|
|
class Square implements Shape {
|
|
constructor(private side: number) {}
|
|
area(): number { return this.side * this.side; }
|
|
}</code></pre>
|
|
<p><strong>I - Interface Segregation Principle</strong></p>
|
|
<blockquote><p>Clients shouldn't depend on interfaces they don't use</p></blockquote>
|
|
<pre><code class="lang-go">// Bad: Fat interface
|
|
type Worker interface {
|
|
Work()
|
|
Eat()
|
|
Sleep()
|
|
}
|
|
|
|
type Robot struct{}
|
|
|
|
func (r Robot) Work() { /* ... */ }
|
|
func (r Robot) Eat() { /* Robots don't eat! */ }
|
|
func (r Robot) Sleep() { /* Robots don't sleep! */ }
|
|
|
|
// Good: Segregated interfaces
|
|
type Worker interface {
|
|
Work()
|
|
}
|
|
|
|
type LivingWorker interface {
|
|
Worker
|
|
Eat()
|
|
Sleep()
|
|
}
|
|
|
|
type Robot struct{}
|
|
func (r Robot) Work() { /* ... */ }
|
|
|
|
type Human struct{}
|
|
func (h Human) Work() { /* ... */ }
|
|
func (h Human) Eat() { /* ... */ }
|
|
func (h Human) Sleep() { /* ... */ }</code></pre>
|
|
<p><strong>D - Dependency Inversion Principle</strong></p>
|
|
<blockquote><p>Depend on abstractions, not concretions</p></blockquote>
|
|
<pre><code class="lang-typescript">// Bad: High-level module depends on low-level module
|
|
class MySQLDatabase {
|
|
save(data: string) { /* MySQL specific */ }
|
|
}
|
|
|
|
class UserService {
|
|
private db = new MySQLDatabase(); // Tight coupling!
|
|
|
|
saveUser(user: User) {
|
|
this.db.save(JSON.stringify(user));
|
|
}
|
|
}
|
|
|
|
// Good: Both depend on abstraction
|
|
interface Database {
|
|
save(data: string): void;
|
|
}
|
|
|
|
class MySQLDatabase implements Database {
|
|
save(data: string) { /* MySQL specific */ }
|
|
}
|
|
|
|
class PostgresDatabase implements Database {
|
|
save(data: string) { /* Postgres specific */ }
|
|
}
|
|
|
|
class UserService {
|
|
constructor(private db: Database) {} // Depend on interface
|
|
|
|
saveUser(user: User) {
|
|
this.db.save(JSON.stringify(user));
|
|
}
|
|
}</code></pre>
|
|
<hr>
|
|
<h3>Concept 2: Code Smells</h3>
|
|
<p><strong>Common Code Smells</strong>:</p>
|
|
<p>| Smell | Description | Fix | |-------|-------------|-----| | <strong>Long Method</strong> | Method > 30 lines | Extract smaller methods | | <strong>Large Class</strong> | Class > 500 lines | Split into multiple classes | | <strong>Long Parameter List</strong> | > 3-4 parameters | Use object/struct | | <strong>Duplicated Code</strong> | Same logic in multiple places | Extract to function | | <strong>Dead Code</strong> | Unused code | Delete it | | <strong>Magic Numbers</strong> | Hardcoded constants | Use named constants | | <strong>Nested Conditionals</strong> | If/else > 3 levels deep | Extract guard clauses | | <strong>Primitive Obsession</strong> | Over-reliance on primitives | Create value objects | | <strong>Feature Envy</strong> | Method uses another class's data more than its own | Move method | | <strong>Data Clumps</strong> | Same group of data everywhere | Create a class |</p>
|
|
<p><strong>Examples</strong>:</p>
|
|
<pre><code class="lang-python"># Smell: Magic Numbers
|
|
def calculate_price(quantity):
|
|
return quantity * 19.99 * 1.08 # What are these?
|
|
|
|
# Fixed: Named Constants
|
|
PRICE_PER_ITEM = 19.99
|
|
TAX_RATE = 1.08
|
|
|
|
def calculate_price(quantity):
|
|
return quantity * PRICE_PER_ITEM * TAX_RATE</code></pre>
|
|
<pre><code class="lang-typescript">// Smell: Long Parameter List
|
|
function createUser(
|
|
name: string,
|
|
email: string,
|
|
age: number,
|
|
address: string,
|
|
phone: string,
|
|
company: string
|
|
) { }
|
|
|
|
// Fixed: Parameter Object
|
|
interface UserData {
|
|
name: string;
|
|
email: string;
|
|
age: number;
|
|
address: string;
|
|
phone: string;
|
|
company: string;
|
|
}
|
|
|
|
function createUser(data: UserData) { }</code></pre>
|
|
<pre><code class="lang-go">// Smell: Nested Conditionals
|
|
func processOrder(order Order) error {
|
|
if order.IsValid() {
|
|
if order.HasInventory() {
|
|
if order.PaymentSucceeded() {
|
|
if order.ShippingAvailable() {
|
|
// Process order
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
// Fixed: Guard Clauses
|
|
func processOrder(order Order) error {
|
|
if !order.IsValid() {
|
|
return ErrInvalidOrder
|
|
}
|
|
if !order.HasInventory() {
|
|
return ErrOutOfStock
|
|
}
|
|
if !order.PaymentSucceeded() {
|
|
return ErrPaymentFailed
|
|
}
|
|
if !order.ShippingAvailable() {
|
|
return ErrShippingUnavailable
|
|
}
|
|
|
|
// Process order
|
|
return nil
|
|
}</code></pre>
|
|
<hr>
|
|
<h3>Concept 3: Code Quality Metrics</h3>
|
|
<p><strong>Cyclomatic Complexity</strong></p>
|
|
<blockquote><p>Measure of code complexity based on number of independent paths</p></blockquote>
|
|
<pre><code class="lang-python"># Complexity: 1 (simple)
|
|
def add(a, b):
|
|
return a + b
|
|
|
|
# Complexity: 4 (moderate)
|
|
def get_discount(user_type, purchase_amount):
|
|
if user_type == "premium":
|
|
if purchase_amount > 100:
|
|
return 0.20
|
|
return 0.10
|
|
elif user_type == "regular":
|
|
if purchase_amount > 100:
|
|
return 0.10
|
|
return 0
|
|
|
|
# Target: Keep functions < 10 complexity</code></pre>
|
|
<p><strong>Code Coverage</strong></p>
|
|
<blockquote><p>Percentage of code executed by tests</p></blockquote>
|
|
<pre><code class="lang-bash"># Good coverage targets:
|
|
# - Critical business logic: 90%+
|
|
# - General codebase: 70-80%
|
|
# - UI/Glue code: 50-60%
|
|
|
|
pytest --cov=myapp --cov-report=html
|
|
# coverage: 78% (good!)</code></pre>
|
|
<p><strong>Maintainability Index</strong></p>
|
|
<blockquote><p>Composite metric: 171 - 5.2 <em> ln(V) - 0.23 </em> G - 16.2 * ln(L)</p>
|
|
<ul><li>V: Halstead Volume (complexity)</li><li>G: Cyclomatic Complexity</li><li>L: Lines of Code</li></ul></blockquote>
|
|
<p>| Score | Maintainability | |-------|-----------------| | 85-100 | Highly maintainable | | 65-85 | Moderately maintainable | | < 65 | Difficult to maintain |</p>
|
|
<p><strong>Code Churn</strong></p>
|
|
<blockquote><p>How often files change</p></blockquote>
|
|
<pre><code class="lang-bash"># High churn = potential quality issues
|
|
git log --format=format: --name-only | sort | uniq -c | sort -rn | head -10
|
|
|
|
# Example output:
|
|
# 47 src/utils/helpers.py # Too much churn!
|
|
# 12 src/models/user.py # Acceptable</code></pre>
|
|
<hr>
|
|
<h2>Patterns</h2>
|
|
<h3>Pattern 1: Readable Code Structure</h3>
|
|
<p><strong>Function Length</strong>:</p>
|
|
<pre><code class="lang-python"># Bad: Long function (100+ lines)
|
|
def process_order(order):
|
|
# 100 lines of mixed concerns
|
|
|
|
# Good: Small, focused functions
|
|
def process_order(order):
|
|
validate_order(order)
|
|
charge_payment(order)
|
|
update_inventory(order)
|
|
send_confirmation(order)
|
|
|
|
# Each function < 20 lines, single responsibility</code></pre>
|
|
<p><strong>Variable Naming</strong>:</p>
|
|
<pre><code class="lang-typescript">// Bad: Unclear names
|
|
let d: number; // What is d?
|
|
let tmp: string; // Temporary what?
|
|
let data: any[]; // What kind of data?
|
|
|
|
// Good: Descriptive names
|
|
let daysUntilExpiration: number;
|
|
let userEmail: string;
|
|
let activeOrders: Order[];</code></pre>
|
|
<p><strong>Comments</strong>:</p>
|
|
<pre><code class="lang-go">// Bad: Redundant comment
|
|
// Increment i by 1
|
|
i++
|
|
|
|
// Bad: Outdated comment
|
|
// Calculate tax rate (7%)
|
|
taxRate := 0.08 // Comment is wrong!
|
|
|
|
// Good: Explain WHY, not WHAT
|
|
// Use exponential backoff to avoid overwhelming the API
|
|
// during high traffic periods
|
|
time.Sleep(time.Duration(math.Pow(2, retries)) * time.Second)</code></pre>
|
|
<hr>
|
|
<h3>Pattern 2: Error Handling</h3>
|
|
<p><strong>Python</strong>:</p>
|
|
<pre><code class="lang-python"># Bad: Silently swallowing errors
|
|
try:
|
|
user = get_user(user_id)
|
|
except:
|
|
pass # What happened?
|
|
|
|
# Good: Specific error handling
|
|
try:
|
|
user = get_user(user_id)
|
|
except UserNotFoundError as e:
|
|
logger.error(f"User {user_id} not found: {e}")
|
|
raise
|
|
except DatabaseError as e:
|
|
logger.error(f"Database error: {e}")
|
|
# Try fallback
|
|
user = get_user_from_cache(user_id)</code></pre>
|
|
<p><strong>Go</strong>:</p>
|
|
<pre><code class="lang-go">// Bad: Ignoring errors
|
|
user, _ := getUser(userID) // What if it fails?
|
|
|
|
// Good: Explicit error handling
|
|
user, err := getUser(userID)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to get user %d: %w", userID, err)
|
|
}</code></pre>
|
|
<p><strong>Rust</strong>:</p>
|
|
<pre><code class="lang-rust">// Bad: Unwrapping everywhere
|
|
let user = get_user(user_id).unwrap(); // Panics on error!
|
|
|
|
// Good: Propagating errors
|
|
let user = get_user(user_id)?; // Returns early if error
|
|
|
|
// Or: Pattern matching
|
|
match get_user(user_id) {
|
|
Ok(user) => process_user(user),
|
|
Err(e) => log::error!("Failed to get user: {}", e),
|
|
}</code></pre>
|
|
<hr>
|
|
<h3>Pattern 3: Testable Code Design</h3>
|
|
<p><strong>Bad: Hard to Test</strong>:</p>
|
|
<pre><code class="lang-typescript">class UserService {
|
|
async createUser(email: string): Promise<User> {
|
|
// Hard-coded dependency!
|
|
const db = new MySQLDatabase();
|
|
const emailService = new SendGridEmailService();
|
|
const logger = new FileLogger();
|
|
|
|
const user = await db.save({ email });
|
|
await emailService.send(user.email, "Welcome!");
|
|
logger.info(`Created user ${user.id}`);
|
|
|
|
return user;
|
|
}
|
|
}
|
|
|
|
// Can't test without real database, email service, file system!</code></pre>
|
|
<p><strong>Good: Easy to Test</strong>:</p>
|
|
<pre><code class="lang-typescript">interface Database {
|
|
save(data: any): Promise<User>;
|
|
}
|
|
|
|
interface EmailService {
|
|
send(to: string, subject: string): Promise<void>;
|
|
}
|
|
|
|
interface Logger {
|
|
info(message: string): void;
|
|
}
|
|
|
|
class UserService {
|
|
constructor(
|
|
private db: Database,
|
|
private emailService: EmailService,
|
|
private logger: Logger
|
|
) {}
|
|
|
|
async createUser(email: string): Promise<User> {
|
|
const user = await this.db.save({ email });
|
|
await this.emailService.send(user.email, "Welcome!");
|
|
this.logger.info(`Created user ${user.id}`);
|
|
return user;
|
|
}
|
|
}
|
|
|
|
// Easy to test with mocks!
|
|
const mockDb = { save: jest.fn() };
|
|
const mockEmail = { send: jest.fn() };
|
|
const mockLogger = { info: jest.fn() };
|
|
const service = new UserService(mockDb, mockEmail, mockLogger);</code></pre>
|
|
<hr>
|
|
<h3>Pattern 4: Code Organization</h3>
|
|
<p><strong>Package Structure</strong>:</p>
|
|
<pre><code># Bad: Organized by type
|
|
src/
|
|
controllers/
|
|
user_controller.py
|
|
order_controller.py
|
|
product_controller.py
|
|
models/
|
|
user.py
|
|
order.py
|
|
product.py
|
|
services/
|
|
user_service.py
|
|
order_service.py
|
|
product_service.py
|
|
|
|
# Good: Organized by feature/domain
|
|
src/
|
|
users/
|
|
controller.py
|
|
model.py
|
|
service.py
|
|
repository.py
|
|
orders/
|
|
controller.py
|
|
model.py
|
|
service.py
|
|
repository.py
|
|
products/
|
|
controller.py
|
|
model.py
|
|
service.py
|
|
repository.py</code></pre>
|
|
<p><strong>Module Cohesion</strong>:</p>
|
|
<pre><code class="lang-python"># Bad: Low cohesion - unrelated functions
|
|
def calculate_tax(amount): ...
|
|
def send_email(to, subject): ...
|
|
def hash_password(password): ...
|
|
|
|
# Good: High cohesion - related functions
|
|
# tax_calculator.py
|
|
def calculate_sales_tax(amount, state): ...
|
|
def calculate_income_tax(income, bracket): ...
|
|
def get_tax_rate(state): ...
|
|
|
|
# email_service.py
|
|
def send_email(to, subject, body): ...
|
|
def send_bulk_email(recipients, subject, body): ...
|
|
def validate_email(email): ...
|
|
|
|
# auth_service.py
|
|
def hash_password(password): ...
|
|
def verify_password(password, hash): ...
|
|
def generate_token(user_id): ...</code></pre>
|
|
<hr>
|
|
<h2>Best Practices</h2>
|
|
<h3>Code Quality Checklist</h3>
|
|
<p><strong>Before Committing</strong>:</p>
|
|
<ul><li>[ ] No commented-out code (delete it, git remembers)</li><li>[ ] No TODO comments (create tickets instead)</li><li>[ ] No magic numbers (use named constants)</li><li>[ ] No functions > 30 lines</li><li>[ ] No classes > 500 lines</li><li>[ ] No duplicate code (DRY principle)</li><li>[ ] Meaningful variable/function names</li><li>[ ] Complex logic has comments explaining WHY</li></ul>
|
|
<p><strong>During Review</strong>:</p>
|
|
<ul><li>[ ] Follows team's style guide</li><li>[ ] Has adequate test coverage</li><li>[ ] No obvious bugs or edge cases</li><li>[ ] Error handling is appropriate</li><li>[ ] Dependencies are necessary</li><li>[ ] Performance is acceptable</li><li>[ ] Security vulnerabilities addressed</li></ul>
|
|
<hr>
|
|
<h2>Anti-Patterns</h2>
|
|
<h3>Common Mistakes</h3>
|
|
<pre><code>❌ Over-engineering: Premature abstraction
|
|
→ Start simple, refactor when needed
|
|
|
|
❌ God objects: Classes that do everything
|
|
→ Follow Single Responsibility Principle
|
|
|
|
❌ Premature optimization: Optimizing before profiling
|
|
→ Make it work, make it right, make it fast
|
|
|
|
❌ Copy-paste coding: Duplicating logic
|
|
→ Extract to shared functions
|
|
|
|
❌ Commenting obvious code: // Set x to 5
|
|
→ Only comment complex/non-obvious logic
|
|
|
|
❌ Inconsistent naming: getUserData() vs fetchUser()
|
|
→ Pick conventions and stick to them
|
|
|
|
❌ Deep nesting: If/else 5+ levels deep
|
|
→ Use guard clauses, early returns
|
|
|
|
❌ Ignoring errors: try { } catch { }
|
|
→ Handle errors explicitly</code></pre>
|
|
<hr>
|
|
<h2>Tools & Automation</h2>
|
|
<h3>Static Analysis Tools</h3>
|
|
<p><strong>Python</strong>:</p>
|
|
<pre><code class="lang-bash"># Linting
|
|
flake8 src/
|
|
pylint src/
|
|
|
|
# Type checking
|
|
mypy src/
|
|
|
|
# Code quality
|
|
radon cc src/ -a # Cyclomatic complexity
|
|
radon mi src/ # Maintainability index
|
|
|
|
# Security
|
|
bandit -r src/</code></pre>
|
|
<p><strong>JavaScript/TypeScript</strong>:</p>
|
|
<pre><code class="lang-bash"># Linting
|
|
eslint src/
|
|
|
|
# Type checking
|
|
tsc --noEmit
|
|
|
|
# Code quality
|
|
npx complexity-report src/</code></pre>
|
|
<p><strong>Go</strong>:</p>
|
|
<pre><code class="lang-bash"># Linting
|
|
golangci-lint run
|
|
|
|
# Cyclomatic complexity
|
|
gocyclo -over 10 .
|
|
|
|
# Security
|
|
gosec ./...</code></pre>
|
|
<h3>Quality Gates in CI</h3>
|
|
<pre><code class="lang-yaml"># .github/workflows/quality.yml
|
|
name: Code Quality
|
|
on: [pull_request]
|
|
|
|
jobs:
|
|
quality:
|
|
runs-on: ubuntu-latest
|
|
steps:
|
|
- uses: actions/checkout@v3
|
|
|
|
- name: Run linters
|
|
run: |
|
|
flake8 src/ --max-complexity=10
|
|
pylint src/ --fail-under=8.0
|
|
|
|
- name: Check test coverage
|
|
run: |
|
|
pytest --cov=src --cov-fail-under=80
|
|
|
|
- name: Security scan
|
|
run: |
|
|
bandit -r src/ -ll
|
|
|
|
- name: Check complexity
|
|
run: |
|
|
radon cc src/ -a -nb --total-average-threshold=B</code></pre>
|
|
<hr>
|
|
<h2>Related Skills</h2>
|
|
<ul><li><strong>engineering-code-review</strong>: Reviewing code for quality issues</li><li><strong>engineering-refactoring-patterns</strong>: Improving code quality through refactoring</li><li><strong>engineering-test-driven-development</strong>: Writing quality code via TDD</li><li><strong>engineering-technical-debt</strong>: Managing quality trade-offs</li><li><strong>engineering-design-patterns</strong>: Applying proven design solutions</li></ul>
|
|
<hr>
|
|
<h2>References</h2>
|
|
<ul><li><a href="https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code by Robert C. Martin</a></li><li><a href="https://en.wikipedia.org/wiki/SOLID">SOLID Principles</a></li><li><a href="https://refactoring.guru/refactoring/smells">Code Smells Catalog</a></li><li><a href="https://en.wikipedia.org/wiki/Cyclomatic_complexity">Cyclomatic Complexity</a></li></ul>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/engineering-code-quality.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |