Stating the obvious — how to code

I’ve seen on Hacker News that people often get confused about things like the “10x programmer” or whether one should write as little code as possible vs finding the most simple solution, etc., so I’m proposing a set of simple and general rules for writing code. Some of them might conflict each other (e.g. writing clear code vs writing little code); in such cases follow the rule that’s first in the list.

0. Use a VCS and write your code as a set of patches

These would be “pull requests”, “merge requests”, “diffs”, or even simple commits. I will call them pull requests. This is very important for several reasons, but I’m putting it here as rule zero because it’s the best tool available for upholding rules 1–4. What I tend to do is review my patch before committing / sending it for review, to make sure it follows the rules.

1. Each pull request should solve a single problem

If a PR doesn’t solve any problems, then it shouldn’t exist. Note that the problem can be business-facing (e.g. “add a button to edit your comment”) or technical (e.g. “changing whitespace throughout the code from tabs to spaces”, or “refactoring X to make it more extensible”). You should make absolutely sure that the thing that you are trying to solve is actually a problem, and that your pull request is actually solving that problem. Apply YAGNI when it makes sense.

If you are trying to solve more than one problem, create multiple pull requests.

2. Each pull request should be straightforward and efficient

You should try to find the solution that solves the problem in a way that is easy to understand by fellow programmers and efficient in terms of execution speed, memory, etc. If you have multiple solutions with different trade-offs between simplicity and efficiency, apply common sense to reach a compromise — though unless the most straightforward solution is either several orders of magnitude slower, or deemed not fast enough by the project’s needs (e.g. a database), you should err on the side of simple code.

3. Each pull request should be minimal

You should not write more code than is needed to solve the problem in a straightforward and efficient way.

4. Communicate with your peers and stakeholders

Unless you’re the sole developer and user of a project, make sure other people involved know what you’re doing and why, and also make sure you know what other people are working on and why. Know your users’ needs. Ask and provide code review.

You can become a better programmer by optimizing several things:

  • understanding what problems to solve, and which are more important to solve than others
  • finding solutions that are easier to understand and more efficient
  • communication
  • discipline in following good practices
  • the speed of solving problems