As a budding programmer (hobbyist), what can I do not to fall into the mistakes others talk about in the comments?
Is there any particular set of mental habits that could lessen the chance of spaghetti occurring, or is it just a matter of when rather than if?
In practice, it's more a matter of mentality and willingness, than any specific knowledge regarding code maintanence. All you need is a couple of articles or a single book about writing clean, maintainable code - after that, the majority of the benefit comes from simply trying to maintain the long term thinking and not getting into a "let's just get this frigging done and go for a beer" mentality. Yes, there's always more you can learn to better structure your code, but simply being aware and _wanting_ to write readable code consistently takes you above 75% of the code out there.
All these comments are good. Also ALWAYS watch out for 'Quick Win': When you do something quick and dirty, mark it up for 'refactoring' (i.e. Tech Debt). When your list of quick and dirty builds up, go and clean it. Do not accumulate tech debt, try to keep it low otherwise you will pay full price later (examples up here).
Another great tip that saved me from tons of refactoring: "The wrong abstraction is worse code duplication". Meaning sometimes duplication of code is better than trying to create the wrong architecture (as long as you mark it in your quick and dirty list).
The best way to learn how not to write spaghetti code is working on spaghetti somebody else wrote. Every big project has some corner with sub-par code quality, so you could volunteer to clean something up, e.g. in Libreoffice or Firefox.
Here's some rule I'm using to keep my code maintainable (to me):
- Line should not be too long (120 max)
- Function should fit into 1 page in the view port of screen, even when your console and debugger take 1/3 bottom part of the screen.
- Variable name should be pronounceable and longer than 3 letters (to prevent name like `i`, `x`, `s`)
- File should not be too long (1000 lines max).
- Return/Exit/Throw as early as possible.
- Comment:
- If an `if` take more than 2 condition, it's worth commenting.
- If a funciton is longer than 10 lines, it's worth commenting.
- All file's worth commenting.
- If you ask yourself "should I add comment", add comment.