Assume there is interface:
type CustomMetrics interface {
Update() error
Init() error
}
This interface will have many different implementations (structs), each implementation will be shipped with New
method, which returns new object of this type, here is example:
type TestMetric struct {
metric IntGauge
}
func (m *TestMetric) Init() error {
// registers the metric in otel metrics, basically deals with exporting it via HTTP
}
func (m *TestMetric) Update() error {
// Contacts another system, parses the data and update the metric value in otel metrics
}
the Update
methods are quite complex in reality. Also they are very different from one another in terms of implementation.
Following this pattern, if I want to instantiate all objects from a single function I will have to create a method similar to:
func InitAllMetrics() []CustomMetrics {
cm := make(CustomMetrics, 0)
testMetric1, err := NewTestMetric()
if err != nil {
return err
}
cm = append(cm, testMetric1)
testMetric2, err := NewTestMetric2()
if err != nil {
return err
}
cm = append(cm, testMetric2)
}
This method will become extremely big(I need to create around 50 metrics), it will be error prone to modify and difficult to test.
Are there any alternatives?