In the end, this question will surely depend on personal preferences. Nevertheless, I would like to dare an attempt to find out which style is the preferred one.
I have recently noticed inconsistencies in my code. I have a struct with some fields. The question now is what is the idiomatic way to edit this field when I need to call a function to get the value I want to set. Do I set the value inside the function, or do I return it and set it in my calling function?
type SuperStruct struct {
OneValue string
AnotherValue string
}
func (s *SuperStruct) makeAnotherValue() {
s.AnotherValue = "Hello there"
}
func main() {
superStruct := SuperStruct{}
superStruct.makeAnotherValue()
}
or (with the same struct)
func (s *SuperStruct) makeAnotherValue() string {
return "Hello there"
}
func main() {
superStruct := SuperStruct{}
superStruct.AnotherValue = superStruct.makeAnotherValue()
}
I know that there are cases where only one of these ways makes sense. But I often find myself in a situation where both are possible. I guess the second way would allow for better guarding, but sometimes that's not an issue.
I think the idiomatic go way would be to remove your function entirely:
func main() {
superStruct := SuperStruct{AnotherValue:"Hello there"}
}
or
func main() {
superStruct := SuperStruct{}
...
superStruct.AnotherValue = "Hello there"
}
Don't build getters/setters/create functions unless they are absolutely necessary, just do the work required. If you're just setting a simple field, you don't need a factory to make the field value in most cases. If you think the function is necessary, it would need to be a lot more complex than this (at least a few lines) and would typically be called NewAnotherValue and not attached to the parent struct.
Every indirection through another function/struct makes the code harder to follow.