From 6f562e72687e09395dab61e1db15cb5b040ff042 Mon Sep 17 00:00:00 2001 From: Paul Buetow Date: Sat, 23 May 2026 21:16:14 +0300 Subject: refactor: reduce GetMetricRegistry() global singleton usage (DIP) Dependency Inversion: scope MetricRegistry as a dependency rather than relying on a global singleton. This enables testing with custom registries and decouples code from global mutable state. Changes: - NewRPN(vars, reg...): accepts optional *MetricRegistry parameter. Defaults to GetMetricRegistry() when not provided (backward compatible). - NewOperations(vars, reg...): accepts optional *MetricRegistry parameter. Defaults to GetMetricRegistry() when not provided (backward compatible). - parseNumberWithMetric(token, reg): requires *MetricRegistry parameter instead of calling GetMetricRegistry() internally. - RPN struct stores metricRegistry field, used by rpn_parse.go for metric lookups (@ prefix and parseNumberWithMetric). - Added Operations.MetricRegistry() getter for external access. All existing callers remain backward compatible via variadic defaults. Tests updated to pass GetMetricRegistry() to parseNumberWithMetric. --- internal/rpn/operations.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) (limited to 'internal/rpn/operations.go') diff --git a/internal/rpn/operations.go b/internal/rpn/operations.go index caed87a..64a0d2d 100644 --- a/internal/rpn/operations.go +++ b/internal/rpn/operations.go @@ -198,14 +198,19 @@ type Operations struct { var _ Operator = (*Operations)(nil) // NewOperations creates a new Operations instance with the given variable store. -func NewOperations(vars VariableStore) *Operations { +// If no registry is provided, defaults to the global MetricRegistry. +func NewOperations(vars VariableStore, reg ...*MetricRegistry) *Operations { consts := NewConstants() + r := GetMetricRegistry() + if len(reg) > 0 && reg[0] != nil { + r = reg[0] + } return &Operations{ vars: vars, consts: consts, mode: FloatMode, // default prefixMode: SI, // default - metricRegistry: GetMetricRegistry(), + metricRegistry: r, } } @@ -241,6 +246,11 @@ func (o *Operations) SetPrefixMode(mode PrefixMode) { o.prefixMode = mode } +// MetricRegistry returns the metric registry used by this Operations instance. +func (o *Operations) MetricRegistry() *MetricRegistry { + return o.metricRegistry +} + // OperatorHandler represents a function that handles an operator. // Returns (result string, handled bool, error error). // result is non-empty only for commands that return immediately (like show, vars). -- cgit v1.2.3