To THIS or not to THIS

A classes methods can often reference its instance state or accept values as parameters. When should we use one technique vs the other?

If you think of an object lifecycle as starting, control, transformation methods. Constructors for starting, all public methods are control methods and private may be transformation methods.

Principle: Encourage pure functions, discourage object state.

Rule 1:

If the method it initializing an object then reference the object properties. 

func (x X) init() { x.foo = 1 }

Rule 2:

If the method is coordinating a request to the object then use the object properties. All methods that coordinate the operations performed on state are control methods.
func (x X) Control() { makeAChange(x.foo); return x.foo }
Rule 3:

If the method is changing an objects state only use parameters. Methods that change state should be simple to test and lend themselves to refactoring to other classes. These are usually private methods.
func (_ X) makeAChange(foo) { return foo + 1 }

No comments: