jmattheis / goverter

Generate type-safe Go converters by simply defining an interface
https://goverter.jmattheis.de/
MIT License
496 stars 46 forks source link

[Questions] When generating converters, is it possible to generate constructor at the same time #45

Closed shuqingzai closed 1 year ago

shuqingzai commented 1 year ago

Have you read the project readme?

Describe your question A clear and concise description of what the question is. Include errors and go source files.

type ResourceConverterImpl struct{}

func NewResourceConverter() gen.ResourceConverter {
    return &ResourceConverterImpl{}
}

func (c *ResourceConverterImpl) ConvertModelToDomain(source *model.Resource) (*types.Resource, error) {
    var pTypesResource *types.Resource
    if source != nil {
        typesResource := c.modelResourceToTypesResource(*source)
        pTypesResource = &typesResource
    }
    return pTypesResource, nil
}

It is a good choice for dependency injection or initialization declaration

jmattheis commented 1 year ago

It would be possible, but you can easily create this method yourself, as it's only three lines of code. Why is there a need for this to be automatically generated?

shuqingzai commented 1 year ago
  1. Interface-oriented coding, only need to instantiate the interface
  2. Life cycle management, if you implement the constructor manually, delete the interface later, and regenerate the conversion code, you also need to manually delete the constructor, which is easily forgotten
jmattheis commented 1 year ago

Life cycle management, if you implement the constructor manually, delete the interface later, and regenerate the conversion code, you also need to manually delete the constructor, which is easily forgotten

I don't understand, if you delete the interface, then there is a compile error on the constructor function. What do you mean with "delete the interface later", the converter interface? If so, then regenerating the conversion code isn't possible because the interface is required for that.