Yes, that is a broad generalization. Yes, broad generalizations are (often) bad. Yes, I see the irony in that. However, tutorials are often bad. The good news is, this is often by design. Tutorials are intended to show you how to do something very specific. This means most basic tutorials are intended to show you how to do that specific thing as succinctly as possible. The problem (or potential problem) with this is that good code is often not particularly succinct. As I mentioned in my previous post, "optimal" code isn't easy to design and what is "optimal" for one scenario might not be fore another. So in this post, I'm going to explore some concepts that are (often) good. Since they are often not followed in tutorials, it stands to reason that tutorials are (often) bad.
OK, not that kind of DRY. DRY means "Don't Repeat Yourself". Tutorials typically keep code in as few places as possible to make it easy to follow the examples. DRY code requires separation of concerns. This means putting your code in the "right" place which means you have to have multiple places to put it. Chances are you need a more complex project/file structure than what a tutorial will show you.
Unless a tutorial is demonstrating some aspect of testing, it most likely doesn't include any tests. Because of this, the code won't necessarily be very testable. Making your code testable requires a certain degree of DRYness since you typically want to test small units of code ("unit tests"). Most modern frameworks support features like dependency injection to improve testability, but these features are often absent from tutorials, so beware of tutorials without any tests.
Testability and maintainability go hand in hand. Maintainability is definitely an art and beauty is in the eye of the beholder when it comes to what "easy to read" code looks like, but there are some good rules of thumb:
- Keep functions short enough to read on the screen.
- Use descriptive names for functions that follow the law of least astonishment
- Avoid unnecessarily concise notations
- Use consistent formatting and spacing
Tutorials probably follow number 4, might follow number 3, and very often ignore 1 and 2.
Putting it All Together
The code in tutorials is not typically well structured. Good structure means your code is DRY, testable, and easy to maintain. When following tutorials, look for opportunities to improve the structure. Develop your own toolbox of reusable code and components. You will quickly find that all projects benefit from having at least 3 components: a "core" set of code not tied to a specific implementation, at least one specific implementation, and tests. Nothing is one-size-fits-all so no one template will match every project, but it's good to have a general approach that prepares you to write "good" code.