vendredi 16 octobre 2020

Refactor similar functions in interface implementations

I have the following interface in where I have some extra data varying in different implementations

type Example interface {
    Name() string
    ImplementThis(commonParam1 int, commonParam2 string)
}

and I have the following implementations

type ExampleImpl1 struct {
    // ...
}

func (ei1 ExampleImpl1) Name() string {
    return "ExampleImpl1"
}

// this does not have extra params
func (ei1 *ExampleImpl1) ImplementThis(commonParam1 int, commonParam2 string) {
    // ...
}

type ExampleImpl2 struct {
    // ...
}

func (ei2 ExampleImpl2) Name() string {
    return "ExampleImpl2"
}

// note the extra parameter
func (ei1 *ExampleImpl2) ImplementThis(commonParam1 int, commonParam2 string, extraParam1 int) {
     // ...
}

I need to group all the example implementations under a map object to reference it from a name

var examplesMap map[string]Example
var exampleImpl1 = &ExampleImpl1{}
var exampleImpl2 = &ExampleImpl2{}

examplesMap[exampleImpl1.Name()] = exampleImpl1
examplesMap[exampleImpl2.Name()] = exampleImpl2

var exampleType = "chosen at runtime"

examplesMap[exampleType].ImplementThis(/* and passing correct params*/)

How can I restructure the code to allow what I want to achieve? I already tried builder and factory patterns but I cannot manage to exit this avoiding the use of interface{} type. Is this the only way? Is there a way in which I can check at compile time the types of the Various Example implementations?

Aucun commentaire:

Enregistrer un commentaire