The concept of "Best Practices" leaves a bad taste in my mouth. Most of the time I see someone reference them, it's either as a tool to avoid learning ("just tell me what to do"), or a tool to silence dissenting ideas ("we shouldn't do that it's not a best practice").
Why, then, would I write something about best practices?
Because they're great starting places for learning! By working backwards from "what do people who have been doing this a while suggest?" and understanding why those suggestions exist, you can learn a ton about both the process and culture of creating software. Sometimes what you'll learn is that respected industry veterans can be full of shit.
Some Guidelines for Writing Fewer Bugs, or "Best Practices"
Your fundamental goals are to reduce the number of things that you have to keep in your head at any given moment, and to rely as little as possible on your own ability to consistently do things right. Humans are fallible creatures, and the fewer chances you give yourself to make mistakes, the fewer mistakes you'll make.
- If you make a thing immutable (let for structs and enums in Swift), you never have to think about what happens if it changes, or what other parts of the code you'll effect if you change it.
- If you split complex functions into several smaller functions that only interact by passing arguments or getting return values, then you limit the amount of code you need to consider when hunting for a bug, and you can test each small piece separately.
- If you understand what things must be true in your code (aka invariants, for example "a person's age must be greater than 0"), and either provide no function that can cause them to be untrue, or check and crash immediately (via precondition() or assert() in Swift) when they're untrue, then you don't have to debug issues caused by incorrect assumptions.
- If you remove possibilities, then you don't need to reason about as many combinations of possibilities. For example, Swift removes the possibility of things being nil unless you specifically ask for it back by marking the thing Optional (aka '?').
- If you put the code for doing different things in different places, you reduce the amount of code you have to look at when something goes wrong. The same is true for putting code that does the same thing in the same place.
- If your program needs to do something that many other programs also need to do, then by using a common solution to it (say, a library that provides the functionality you need) you can take advantage of community knowledge and avoid having to redo all the work and testing that others have already done.
-
If you limit the amount of time you spend working, and take regular breaks, you'll get more out of the time you do spend.
Other writing about programming