How not to write ill-organized code in Go
My first belief is that efficient web development requires safe and well-organized code. By using an inversion mental model and focusing on avoiding ill-organized or bad code, we can lead to well-organized code.
An example of bad code is a single-file web API, where the entire app is written in one file. This makes it difficult to navigate and understand. Look at below structure:
So, how can we make it better? This leads to my second belief that untested code is bad code. An obvious approach to make it easier to test main.go is to separate code related to RDBMS and the rest, resulting in two layers of code:
Now, we can probably test main.go somewhat easier by making an HTTP request to main.go and faking function calls to the DB layer. This allows us to simulate multiple scenarios by controlling returns from fake DB layers, which I call test doubles.
We could stop here, or we could continue to make things easier to test by introducing another layer:
Recommended by LinkedIn
To make the code less bad, separate main.go into transport, business, and DB layers. Avoid branches and loops in the transport and DB layers and keep them in the business layer. This makes the business layer easy to test, with high code coverage and quality unit tests by incorporating test doubles on its dependencies (the DB layer). This approach can help achieve less bad code.
Testing business logic is important, but how about the rest especially db Layer? we have two options:
First option is clear but can be challenging, while the second option is questionable but might be interesting and more fit to our needs.
For the second option, we do it by eliminate branching and looping in the DB layer and use code generators like Sqlc. Sqlc can generate code from a query and schema, minimizing the need for testing. If the queries are correct, generated functions will also work properly, reducing the need for testing the DB layer. Then, we could consider that we have less bad code even if no test in place.
Does this mean our code is now good? Maybe, or maybe not, but we can safely say it's less bad code.
Senior Quality Assurance Engineer
3yGood article, panutan 👏🏻
Software Engineer
3yCommon best practise to orgainzed code is by using code architecture like port and adapter or clean architecture. I've been write a code generator for those need. You may visit my opensource project here to learn more : https://github.com/mirzaakhena/gogen