Code should be easy to read. The reader should be able to quickly grasp the code's intent.
Core Patterns
Separating code that does not execute simultaneously
❌ viewer/admin logic mixed in one component:
function SubmitButton() {
const isViewer = useRole() === "viewer";
useEffect(() => {
if (isViewer) return;
showButtonAnimation();
}, [isViewer]);
return isViewer ? (
<TextButton disabled>Submit</TextButton>
) : (
<Button type="submit">Submit</Button>
);
}
✅ Separated by branch:
function SubmitButton() {
const isViewer = useRole() === "viewer";
return isViewer ? <ViewerSubmitButton /> : <AdminSubmitButton />;
}
function ViewerSubmitButton() {
return <TextButton disabled>Submit</TextButton>;
}
function AdminSubmitButton() {
useEffect(() => { showButtonAnimation(); }, []);
return <Button type="submit">Submit</Button>;
}
Naming complex conditions
❌ Can't immediately see what the condition means:
if (user.age >= 18 && !user.isBanned && user.emailVerified) { ... }
✅ Expressing intent through names:
const canPurchase = user.age >= 18 && !user.isBanned && user.emailVerified;
if (canPurchase) { ... }
Quick Reference
| Code Smell | Improvement Method |
|---|---|
| Nested ternary operators | ifUse statements or early return |
Complex conditions a && !b || c |
Give meaningful names: const canProceed = ... |
| Multiple branches interleaved | Separate into distinct components per branch |
| Jumping back and forth through the code | Manage conditions as an object that shows them at a glance |
Cautions
- Don't over-abstract even simple logic
- Improve the code itself instead of adding comments to bad code
- Don't create deep hierarchies for "future flexibility"
Reference: https://frontend-fundamentals.com/code-quality/readable/