Defer to Clean Up

Use defer to clean up resources such as files and locks.

BadGood
  1. p.Lock()
  2. if p.count < 10 {
  3. p.Unlock()
  4. return p.count
  5. }
  6.  
  7. p.count++
  8. newCount := p.count
  9. p.Unlock()
  10.  
  11. return newCount
  12.  
  13. // easy to miss unlocks due to multiple returns
  1. p.Lock()
  2. defer p.Unlock()
  3.  
  4. if p.count < 10 {
  5. return p.count
  6. }
  7.  
  8. p.count++
  9. return p.count
  10.  
  11. // more readable

Defer has an extremely small overhead and should be avoided only if you canprove that your function execution time is in the order of nanoseconds. Thereadability win of using defers is worth the miniscule cost of using them. Thisis especially true for larger methods that have more than simple memoryaccesses, where the other computations are more significant than the defer.