- **Epistemic status:** #seedlings
Programming by coincidence is the act of working on a problem that at first glance might be solved, but by not understanding the reason it was solved the code produced is error-prone. Whenever this piece of code fails, the developer won't know what made it fail in the first place. A few examples of when we rely on coincidences are the following:
- **Accidents of implementation:** These are pieces of code that happen because that is the way the code is currently written. You might call a routine that responds in a particular way, but the author of the code never intended the routine to be utilized in such a way. Whenever this routine gets “fixed” your code will break.
- **Close enough code:** When a piece of code is fixed manually on more than two locations because the result is only off by a small amount. This issue is a symptom of a larger architectural issue. [[Avoid software rot]] by finding the root of the problem and solving it, eliminating the problem altogether.
- **Phantom patterns:** When code works in some cases and in others it does not. It might be a difference of environment, a bug, a race condition, etc. Don't diagnose the issue right away, just because you have seen this before. First, you must prove it.
- **Implicit Assumptions:** These can be assumptions when gathering requirements for a particular task, tests that assume a particular routine will have tests to begin with, or that a particular task does or doesn't need particular functionality. Always make sure to test these assumptions, making sure each piece of code is verified.
To avoid programming by coincidence, you can do the following:
- Be aware of what you are doing
- Document your assumptions
- Proceed from a plan. This can be in your head or a whiteboard.
- Try to explain the code like you would to a junior programmer. If you can't explain it, you don't understand it
- Test your code and assumptions
- Prioritize your efforts
- Don't let existing code dictate future code. Be ready to refactor code when necessary
---
## References
- Thomas, David, and Andrew Hunt. _The Pragmatic Programmer, 20th Anniversary Edition: Journey to Mastery_. Second edition. Boston: Addison-Wesley, 2019.