
Alongside SOLID, several other world-class coding principles, architectural patterns, and practical disciplines keep a codebase clean, maintainable, and scalable over time.
1. Core Design Philosophy Principles (The Classics)
- DRY (Don’t Repeat Yourself):“Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.”
- Goal: Eliminate duplication of logic, data, and business rules.If you change a rule, you should only have to change it in one place.
- Caution: Avoid “accidental duplication” (where two pieces of code look similar today by coincidence but will evolve differently tomorrow). Over-abstracting too early creates tightly coupled code.
- KISS (Keep It Simple, Stupid):Prioritize straightforward solutions over overly clever or complex designs.
- Goal: Code is read far more often than it is written.Simple code is easier to debug, scale, and hand off to other developers.
- YAGNI (You Aren’t Gonna Need It): Never build functionality, configuration options, or abstraction layers “just in case” you need them later.
- Goal: Prevent over-engineering. Build for current requirements; refactor later when real requirements emerge. Speculative code adds unnecessary technical debt.
2. Structural & Architectural Principles
- Separation of Concerns (SoC): Divide a computer program into distinct sections, where each section addresses a separate concern (e.g., separating business logic from UI rendering, and data access from business logic).
- Law of Demeter (LoD / Principle of Least Knowledge): A module should only talk to its immediate “friends” and not know about the internal details of objects it interacts with (e.g., avoid long method-chaining like
a.getB().getC().doSomething()). This minimizes ripple effects when code changes. - Composition Over Inheritance: Favor building complex behavior by combining small, focused objects/components rather than creating deep, rigid class inheritance hierarchies, which can quickly become brittle.
3. Team & Workflow Practices
- The Boy Scout Rule:“Leave the campground cleaner than you found it.” Whenever you touch a piece of code, fix a minor bug, clean up a messy variable name, or extract a small method. Incremental refactoring prevents codebases from rotting.
- Convention over Configuration:Relying on standardized project structures, naming rules, and frameworks reduces cognitive load and eliminates endless debates about trivial formatting or folder structures.
- Test-Driven Development (TDD) & Automated Testing: Writing tests (unit, integration) either right before or alongside your implementation forces code to be modular, loosely coupled, and inherently testable.
Summary Checklist for High Code Quality
| Principle | What it Solves | Rule of Thumb |
| SOLID | Tightly coupled architecture | One class, one job; design for extension. |
| DRY | Code and logic duplication | Centralize authoritative business logic. |
| KISS | Unnecessary complexity | Choose the most readable, straightforward approach. |
| YAGNI | Speculative over-engineering | Build what is needed today. |
| Boy Scout | Gradual codebase degradation | Leave every touched file a little better than you found it. |
Here is how these core principles look in practice using PHP. Each example contrasts a violation of the principle with a clean, refactored implementation.
1. DRY (Don’t Repeat Yourself)
The Problem: Duplicate validation or calculation logic scattered across multiple classes or methods. If the business rule changes, you have to update it everywhere.
PHP Example:
PHP
// Bad: Duplicate discount logic
class RegularCustomer {
public function calculateTotal(float $amount): float {
return $amount - ($amount * 0.05); // 5% discount
}
}
class VipCustomer {
public function calculateTotal(float $amount): float {
return $amount - ($amount * 0.05); // Duplicated 5% logic (should be different, but copy-pasted by mistake)
}
}
// Good: Centralized logic into a single reusable service/method
class DiscountService {
public function applyDiscount(float $amount, float $percentage): float {
return $amount - ($amount * $percentage);
}
}
2. KISS (Keep It Simple, Stupid)
The Problem: Over-engineering a simple task using excessive abstraction, reflection, or overly complex nested ternaries.
PHP Example:
PHP
// Bad: Overly complex and clever ternary chain
function getStatusBadge(string $status): string {
return $status === 'active' ? 'Green' : ($status === 'pending' ? 'Yellow' : ($status === 'banned' ? 'Red' : 'Gray'));
}
// Good: Straightforward, readable guard clauses or match expression (PHP 8+)
function getStatusBadge(string $status): string {
return match ($status) {
'active' => 'Green',
'pending' => 'Yellow',
'banned' => 'Red',
default => 'Gray',
};
}
3. YAGNI (You Aren’t Gonna Need It)
The Problem: Building generalized, highly configurable frameworks for features you don’t need yet.
PHP Example:
PHP
// Bad: Over-engineered for a requirement that doesn't exist yet
class Logger {
// Built extensible driver architecture "just in case" we switch from files to AWS S3, Redis, or Syslog later
public function log(string $message, string $driver = 'file', array $options = []): void {
// 150 lines of dynamic factory loading code here...
}
}
// Good: Build what is needed today
class Logger {
public function log(string $message): void {
file_put_contents(__DIR__ . '/app.log', $message . PHP_EOL, FILE_APPEND);
}
}
4. Separation of Concerns (SoC)
The Problem: Blending HTTP handling, database queries, and business calculations all inside one massive controller or script.
PHP Example:
PHP
// Bad: Controller handles routing, database connection, validation, and HTML rendering all at once
class UserController {
public function register() {
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$stmt = $pdo->prepare("INSERT INTO users (email) VALUES (?)");
$stmt->execute([$_POST['email']]);
echo "<h1>Welcome!</h1>";
}
}
// Good: Controller delegates to a Service and Repository
class UserController {
private UserService $userService;
public function __construct(UserService $userService) {
$this->userService = $userService;
}
public function register(array $data) {
$this->userService->registerUser($data['email']);
return ['status' => 'success'];
}
}
5. Composition Over Inheritance
The Problem: Deep inheritance trees (Dog extends Animal, FlyingDog extends Dog…) that become rigid and impossible to maintain when behavior combinations change.
PHP Example:
PHP
// Bad: Rigid inheritance hierarchy
class Animal {}
class Bird extends Animal { public function fly() { /* ... */ } }
// What if we have a robot duck or a penguin that doesn't fly? Inheritance breaks down.
// Good: Composing behaviors using interfaces and injected objects
interface FlyBehavior {
public function fly(): string;
}
class FastFly implements FlyBehavior {
public function fly(): string { return "Flying super fast!"; }
}
class Duck {
private FlyBehavior $flyBehavior;
public function __construct(FlyBehavior $flyBehavior) {
$this->flyBehavior = $flyBehavior;
}
public function performFly(): string {
return $this->flyBehavior->fly();
}
}


