npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

program-by-coincidence-demo

v1.0.0

Published

A demo showing programming by coincidence vs intentional code

Readme

Programming by Coincidence Demo

CI

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 file

The Problem: Before Version

The before/discount.ts file contains code that "works" but has several issues:

Issues in the Before Version

  1. 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?
  2. Unclear Variable Names

    • d - What does this stand for? Discount? Dollar? Duration?
    • amount, type - Too generic; what type of amount? What type of type?
  3. Hidden Assumptions

    • Assumes amount is always positive (what if it's negative?)
    • Assumes type is 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?
  4. No Validation

    • No error handling for invalid inputs
    • Silent failures or unexpected behavior for edge cases
  5. 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

  1. 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
  2. Explicit Validation

    if (amount < 0) {
      throw new Error('Purchase amount cannot be negative');
    }
    • Fails fast with clear error messages
    • Documents assumptions about valid inputs
  3. Clear Variable Names

    • discountAmount instead of d
    • discountRate instead of magic numbers
    • maximumDiscount makes the capping logic explicit
  4. Documented Business Rules

    • JSDoc comments explain what each function does
    • Constants document thresholds and bonus amounts
    • Comments explain why certain checks exist
  5. Type Safety

    • CustomerType type alias makes valid values explicit
    • Validation ensures only valid types are accepted

Running the Demo

Setup

npm install

Build

npm run build

Run Tests

# Test both versions
npm test

# Test only the before version
npm run test:before

# Test only the after version
npm run test:after

Key Takeaways

Why This Matters

  1. Maintainability: When requirements change (e.g., "add a new customer type"), the after version is much easier to modify
  2. Debugging: When something goes wrong, the after version makes it clear what the code is supposed to do
  3. Onboarding: New developers can understand the after version much faster
  4. 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