program-by-coincidence-demo
v1.0.0
Published
A demo showing programming by coincidence vs intentional code
Maintainers
Readme
Programming by Coincidence Demo
This project demonstrates the difference between programming by coincidence and intentional programming through a discount calculation example.
🔗 Repository: https://github.com/KyPython/program-by-coincidence
What is "Programming by Coincidence"?
Programming by coincidence occurs when code appears to work, but only because of:
- Accidental behavior that happens to produce correct results in some cases
- Hidden assumptions that aren't documented or validated
- Magic numbers whose meaning is unclear
- Implicit dependencies on implementation details
The code "works" until it doesn't—when requirements change, edge cases appear, or someone else needs to maintain it.
Project Structure
.
├── before/ # Coincidentally-working code
│ └── discount.ts # Unclear, magic numbers, hidden assumptions
├── after/ # Intentional, refactored code
│ └── discount.ts # Named constants, documented, explicit
├── tests/ # Tests that work for both versions
│ └── discount.test.ts
└── README.md # This fileThe Problem: Before Version
The before/discount.ts file contains code that "works" but has several issues:
Issues in the Before Version
Magic Numbers
0.1,0.2,0.3- What do these represent? Are they percentages? Rates?100,500- Why these thresholds? What do they mean?10,20- What are these bonus amounts?
Unclear Variable Names
d- What does this stand for? Discount? Dollar? Duration?amount,type- Too generic; what type of amount? What type of type?
Hidden Assumptions
- Assumes
amountis always positive (what if it's negative?) - Assumes
typeis always one of the expected strings (what if it's not?) - Relies on implicit string comparison order
- The discount capping logic (
if (d > amount)) is a safeguard, but why is it needed? Is it a business rule or a bug fix?
- Assumes
No Validation
- No error handling for invalid inputs
- Silent failures or unexpected behavior for edge cases
Unclear Intent
- Why are there bonus discounts? What's the business logic?
- Is the discount a percentage or absolute amount? (It's actually both!)
The Solution: After Version
The after/discount.ts file refactors the code to be intentional:
Improvements in the After Version
Named Constants
const DISCOUNT_RATES = { STANDARD: 0.1, // 10% discount for standard customers PREMIUM: 0.2, // 20% discount for premium customers VIP: 0.3, // 30% discount for VIP customers };- Clear meaning: these are discount rates (percentages)
- Self-documenting: comments explain the business logic
Explicit Validation
if (amount < 0) { throw new Error('Purchase amount cannot be negative'); }- Fails fast with clear error messages
- Documents assumptions about valid inputs
Clear Variable Names
discountAmountinstead ofddiscountRateinstead of magic numbersmaximumDiscountmakes the capping logic explicit
Documented Business Rules
- JSDoc comments explain what each function does
- Constants document thresholds and bonus amounts
- Comments explain why certain checks exist
Type Safety
CustomerTypetype alias makes valid values explicit- Validation ensures only valid types are accepted
Running the Demo
Setup
npm installBuild
npm run buildRun Tests
# Test both versions
npm test
# Test only the before version
npm run test:before
# Test only the after version
npm run test:afterKey Takeaways
Why This Matters
- Maintainability: When requirements change (e.g., "add a new customer type"), the after version is much easier to modify
- Debugging: When something goes wrong, the after version makes it clear what the code is supposed to do
- Onboarding: New developers can understand the after version much faster
- Confidence: Explicit validation and documentation give confidence that edge cases are handled
Specific Changes That Made the Code Intentional
| Before | After | Why It Matters |
|--------|-------|----------------|
| d = amount * 0.1 | discountAmount = amount * DISCOUNT_RATES.STANDARD | The constant name reveals it's a discount rate |
| if (amount > 100) | if (amount > PURCHASE_THRESHOLDS.SMALL_BONUS) | The constant name explains this is a threshold for bonuses |
| No validation | if (amount < 0) throw new Error(...) | Explicitly documents and enforces assumptions |
| d variable | discountAmount | The name reveals what the variable represents |
| Silent behavior | if (finalPrice < 0) throw new Error(...) | Documents that negative prices should never happen |
Further Reading
- "The Pragmatic Programmer" by Andrew Hunt and David Thomas - Chapter on "Programming by Coincidence"
- "Clean Code" by Robert C. Martin - Chapter on "Meaningful Names"
- "Refactoring" by Martin Fowler - Techniques for improving code clarity
License
MIT
