The Hidden Power of Humble Interfaces (GopherCon Singapore 2017)

The Hidden Power of Humble Interfaces (GopherCon Singapore 2017)

Learn how to design your own interfaces in Go that are simple yet powerful – just like io.Reader and error. Discover the techniques for correctly identifying the places where interfaces will improve our code, and the specific steps to ensuring that our interfaces are as powerful as they can be.

94dcff33cbdf74b5d785369ac54bc1a8?s=128

Aditya Mukerjee

May 26, 2017
Tweet

Transcript

  1. The Hidden Power of Humble Interfaces Aditya Mukerjee @ChimeraCoder GopherCon

    Singapore May 26, 2017
  2. @chimeracoder

  3. None
  4. None
  5. Why use interfaces? • Write less code • Write robust

    code • Write flexible code @chimeracoder
  6. Interfaces: The Basics

  7. @chimeracoder

  8. io.* interfaces @chimeracoder

  9. Composite interfaces @chimeracoder

  10. Interface helper functions @chimeracoder

  11. What makes the io interfaces powerful? • Abstracting a lot

    of common functionality • Lots of granularity • Plethora of helper functions @chimeracoder
  12. What makes error powerful? • Abstracts no functionality • Provides

    no granularity • Provides (almost) no helper functions @chimeracoder
  13. So what makes a powerful interface, anyway? @chimeracoder

  14. Humility and Discipline • Keep interfaces humble • Writing interfaces

    forces you to define the minimum required contract for using your types • Keep interfaces disciplined • Writing interfaces allows the compiler to enforce this contract @chimeracoder
  15. type Foo struct interface { } @chimeracoder

  16. Why Gophers avoid interfaces • Afraid of writing an interface

    that is too complicated • Afraid of specifying the wrong methods @chimeracoder
  17. How I Learned To Stop Worrying and Love the interface

    • Interfaces reveal the assumptions you’re already making • “If it’s there, you will use it” @chimeracoder
  18. Every time you access a field or method, you’re making

    an assumption @chimeracoder
  19. So how should I design these interfaces? @chimeracoder

  20. Writing interfaces like io.* • Don’t write helper methods until

    you actually find you need them • The contracts provided by each should be minimal • Create composite interface types @chimeracoder
  21. Writing interfaces like error • Ask interfaces how they behave

    @chimeracoder
  22. What if structs could never be exported? @chimeracoder

  23. Aditya Mukerjee @chimeracoder https://github.com/ChimeraCoder Thank you!