一次 GO 项目重构的疑问

12次阅读

共计 539 个字符,预计需要花费 2 分钟才能阅读完成。

type A struct {
   a ComponentA
   b ComponentB
   d ComponentD
}
func NewA(a ComponentA, b ComponentB, d ComponentD) {}
type B struct {
   b ComponentB
   c ComponentC
   d ComponentD
}
func NewB(b ComponentB, c ComponentC, d ComponentD) {}


// 大概有十几个这样的 struct
....

这十几个 struct 都有一些共同的变量(当然也不是完全一模一样)。
现在是每个结构体的 New 方法传的参数都不一样。当然这十几个 struct 其实做的功能比较相似(每个 struct 其实是 k8s 里面 crd 的 controller),代码结构也有一定的相似性。

现在重构后的代码

type Common struct {
   a ComponentA
   b ComponentB
   c ComponentC
   d ComponentD
   // 一共大概 20 几个
   ...
}

type A struct {*Common}
type B struct {*Common}

这样重构后,每个结构体的 New 方法的参数就很简单,只要传一个 Common 就好了。
但是,这样每个结构体其实引入了一些自己不需要的东西,我自己感觉不是特别好。

各位大佬怎么看?

正文完
 0