1. Init() functions are run before any function in the package, from the first view, it is good to use them as package constructor. In reality, package initializing via init() function will add complexity for your tests, understanding application flows, extendibility of code, etc
2. For example, you decided to init DB connection in the init() function. After this decision, you cannot simply mock DB in your package (or use another init() function in your tests)
3. Let's imagine you have several init() functions in your project. They will be run in "imports order". For example, main.init()->storage.init()->db.init() will be run in order from last to first. What will be if you have ten or more init() functions? I'll call it "init() hell".
4. Moreover, #Golang does not guaranty order of init() functions runs if these functions are located in "tails" of dependence map
5. So, a lot of init() functions make you code untestable and unreadable. With init() functions interface mocking became a rocker science with magic inits, env variables, etc
6. If your library uses init() function for initializing (instead of NewSmth method) - it's really hard to use your library with custom configuration.
7. Cases where init() functions in #Golang are ok:
- single init() function near main() function
- for reading environment variables (but I prefer flags)
8. Cases where init() functions in #Golang are bad:
- create a database connection
- initialization of cache
- initialization network connections
9. Use dependency injection instead (probably without DI container)! Create all required objects with parameters form ENV in your main() function. Push dependencies in the constructor.
10. For example, you have a dependency map main->service->storage->db. Your code int main() function will be like this: