High coupling with the config package

As we saw in our dependency graph, just about everything depends on the config package. The primary cause of this is code that directly references a public global variable to configure itself. The first issue with this is how it affects the tests. All tests now pretty much make sure that the config global has been properly initialized before being run. Because all of the tests are using the same global variable, we are forced to choose between not changing the config, which hampers our ability to test, or running the tests in serial, which wastes our time.

Let's look at an example, as shown in the following code:

// bind stop channel to context
ctx := context.Background()

// start REST server
server := rest.New(config.App.Address)
server.Listen(ctx.Done())

In this code, we are starting our REST server and passing it the address (host and port) to bind to. If we decided that we wanted to start multiple servers to test different things in isolation, then we would have to change the value stored in config.App.Address. However, by doing so in one test, we could accidentally influence a different test.

The second issue doesn't appear as often, but this coupling also means that this code cannot be easily used by other projects, packages, or use cases beyond its original intent.

The final issue is perhaps the most annoying: you cannot use custom data types, defined outside of the Config package, in your config as a result of a circular dependency issue.

Consider the following code:

// Currency is a custom type; used for convenience and code readability
type Currency string

// UnmarshalJSON implements json.Unmarshaler
func (c *Currency) UnmarshalJSON(in []byte) error {
var s string
err := json.Unmarshal(in, &s)
if err != nil {
return err
}

currency, valid := validCurrencies[s]
if !valid {
return fmt.Errorf("'%s' is not a valid currency", s)
}

*c = currency

return nil
}

Say that your config included the following:

type Config struct {
DefaultCurrency currency.Currency `json:"default_currency"`
}

In this case, any attempt to use the config package in the same package as our Currency type would be prevented.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.171.253