go结构填充:指针接收器vs返回值



从代码可读性/维护/最佳实践的角度寻找一个好的阅读参考或分享一个更好的经验。

如何给struct字段赋值有两个选项:

  • 调用返回值并在主代码中执行显式赋值的函数/方法
  • 使用指针接收器方法并在方法中填充结构体。

在这里我并不关心代码的效率,而是更关心代码的可读性和未来的维护。第一种方法使主代码更加混乱,但允许查看从一个地方填充了哪些字段。第二种方法使主代码更简洁,但需要跳转到方法并查看哪些字段被填充。我想知道每种方法的优缺点,是否有其他方法可以解决可读性问题。

选项1 -详细的主代码

type Customer struct {
ID           int
FName        string
LName        string
DOB          string
SacredNumber string
NotYet       string
}
func (c *Customer) fillMyCustomerGeneralWReturn() (fname, lname, dob string) {
fname = getFNameByID(c.ID)
lname = getLNameByID(c.ID)
dob = getDOBByID(c.ID)
return fname, lname, dob
}
func (c *Customer) fillMyCustomerSacredInfoWReturn() string {
return getSacredNumberByIDFromVenus(c.ID)
}
func main() {
cust := Customer{ID: 5}
cust.FName, cust.LName, cust.DOB = cust.fillMyCustomerGeneralWReturn()
cust.SacredNumber = cust.fillMyCustomerSacredInfoWReturn()
}

选项2 -更干净的主代码,但更少的可见性


type Customer struct {
ID           int
FName        string
LName        string
DOB          string
SacredNumber string
NotYet       string
}
func (c *Customer) fillMyCustomerGeneral() {
c.FName = getFNameByID(c.ID)
c.LName = getLNameByID(c.ID)
c.DOB = getDOBByID(c.ID)
}
func (c *Customer) fillMyCustomerSacredInfo() {
c.SacredNumber = getSacredNumberByIDFromVenus(c.ID)
}
func main() {
cust := Customer{ID: 5}
cust.fillMyCustomerGeneral()
cust.fillMyCustomerSacredInfo()
}

谢谢你的建议。我想应该是这样的:

type Customer struct {
ID           int
FName        string
LName        string
DOB          string
SacredNumber string
NotYet       string
}
type CustomerRepository struct {
}
func (*CustomerRepository) FindByID(c int) *Customer {
var returnCustomer Customer
returnCustomer.ID = c
returnCustomer.FName = getFNameByID(c)
returnCustomer.LName = getLNameByID(c)
returnCustomer.DOB = getDOBByID(c)
return &returnCustomer
}
func (*CustomerRepository) SetSacredNumber(c *Customer) {
c.SacredNumber = getSacredNumberByIDFromVenus(c.ID)
return
}
func main() {
var customerRepo CustomerRepository
cust := customerRepo.FindByID(5)
customerRepo.SetSacredNumber(cust)
fmt.Println(*cust)
}

最新更新