Home > Backend Development > Golang > Avoid the Go init function

Avoid the Go init function

Patricia Arquette
Release: 2024-12-19 11:24:18
Original
963 people have browsed it

Avoid the Go init function
Image generated with AI

I get wary whenever I see a Go package using an init function. Init functions can be helpful in certain situations, but most people misuse them.

What is an Init function? ?

In Go, the function init() is executed as part of package initialization right after variables are initialized and values are set.

This process happens if a package is imported regardless of what within the package is used.

I often see logic within the init functions that should never be there.

  • Creating instances of a struct

  • Populating data within a struct

  • Initialization of other dependencies

The problem is testing.

Testing the happy path might be easy enough, but what about error scenarios?

If you add logic within the init functions that could behave differently under different conditions, it becomes challenging to duplicate these scenarios.

Remember, the key to building reliable software is to write tests that run the same functions repeatedly with different inputs to validate different outcomes. It isn’t easy to do that with init functions, so people don’t write those tests.

Overusing the init function ultimately makes code harder to test and maintain and unreliable.

My recommendation is to avoid the init function altogether. Usually, using a constructor like a New() function is the way to go.


The above is the detailed content of Avoid the Go init function. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template