我正在学习 Go,并想知道在某些情况下,在 Golang 中根据消费者代码将如何处理该结构来创建多个interface变体是否被认为是好的/好的/典型的(鼓励?)实践?struct
我对此表示怀疑,因为我有一个结构对象,可以说它在我的代码库中做了太多事情,并且我想添加一些测试并仅模拟该结构的某些用法/使用者。说我有,
对于(人为的)示例,环境结构
// Environment/env.go
package env
type Environment struct {
sunny bool,
fullMoon bool,
temp float64
// ...
}
func (e *Environment) IsSunny() bool {
return e.sunny
}
func (e *Environment) IsFullMoon() bool {
return e.fullMoon
}
func (e *Environment) GetTemp() float64 {
return e.temp
}
上面的结构体具有与一些环境条件(白天和夜间)相关的属性和方法。
然后这个结构有多个消费者,但每个消费者interface只关心可用方法的子集:
// daytime.go
type DayEnv interface {
IsSunny() bool
GetTemp() float64
}
func getDaytime(de DayEnv) {
sunStatus := getSunStatus(de)
temp := getDayTemp(de)
fmt.Printf("Today is %s and temperature is %s", sunStatus, temp)
}
// func getSunStatus(de DayEnv) string {}
// func getDayTemp(de DayEnv) string {}
// nightTime.go
type NightEnv interface {
IsFullMoon() bool
GetTemp() float64
}
func getNighttime(ne NightEnv) {
moonPhase := getMoonPhase(ne)
temp := getNightTemp(ne)
fmt.Printf("Tonight the moon is %s and temperature is %s", moonPhase, temp)
}
// func getMoonPhase(ne NightEnv) string { }
// func getNightTemp(ne NightEnv) string { }
在我看来,虽然创建一个只关心结构方法子集的新接口使事情变得更加灵活,但拥有如此多(部分)接口重复并根据需要或在任何地方散布它们也感觉相当懒惰或错误他们被消耗了。我意识到这个例子有点做作,但是在更大的范围内(就像很多很多消费者),或者也许一个文件具有x相同结构的接口......这种方法有什么问题吗?
牛魔王的故事
胡子哥哥
相关分类