I try to have as many pure functions as possible, but if I can't, I at least try to make the side effects as explicit as possible.
Here is an example (in Go)
type State struct {
count int
}
func (s *State) IncreaseCount() *State {
s.count += 1
return s
}
func main() {
s := new(State)
s = s.IncreaseCount()
}
Since s
is a pointer, s.IncreaseCount()
would be sufficient.
I find s = s.IncreaseCount()
makes it more obvious that s
has changed.
But is this a good practise? Or it just makes the code more complicated than it could be?
As a side note, removing the pointer would actually make IncreaseCount
a pure function:
func (s State) IncreaseCount() State {
s.count += 1
return s
}
but imagine State
is a big complicated struct and we cannot afford copying it.