Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Data abstraction in Golang

mikedebo
September 19, 2013

Data abstraction in Golang

Talk given to the Go Meetup group 19-Sep-2013.

Code lives at https://github.com/MichaelDiBernardo/golang-adts

mikedebo

September 19, 2013
Tweet

More Decks by mikedebo

Other Decks in Programming

Transcript

  1. Programming “in” “Programmers who program ‘in’ a language limit their

    thoughts to constructs that the language directly supports. If the language tools are primitive, the programmer's thoughts will also be primitive.”
  2. Programming “into” “Programmers who program ‘into’ a language first decide

    what thoughts they want to express, and then they determine how to express those thoughts using the tools provided by their specific language.” - Code Complete 2nd ed (Steve McConnell)
  3. signature TREE= sig datatype 'a tree = Lf | Node

    of 'a * 'a tree * 'a tree val size: 'a tree -> int end structure T:> TREE = struct datatype 'a tree = Lf | Node of 'a * 'a tree * 'a tree fun size Lf = 0 | size(Node(_,t1, t2)) = 1 + size t1 + size t2 end
  4. Programming models • Easier to models that are idiomatic to

    the language • Many concepts are independent of model • But what about implementation of these concepts?
  5. ADTs "The general technique of isolating the parts of a

    program that deal with how data objects are represented from the parts of a program that deal with how data objects are used is a powerful design methodology called data abstraction." - Structure and Interpretation of Computer Programs pp.80
  6. ADTs • Abstract type (name) • Operations on that type

    • Preconditions • Postconditions • Invariants
  7. ADTs - Why? • Note that reuse was not a

    strong motivator for these, historically • Re-use was a later movement (esp. OO) • The focus of this talk is not on reuse!
  8. Rational ADT • Create • Convert to human-readable repr •

    Add • Invariant: Should always be in lowest terms
  9. “Implicit” Interfaces "Every type has an interface, which is defined

    to be the set of methods which operate on that type." - Ian Lance Taylor in “Learning Go”
  10. Summary • Using type + methods = implicit interface •

    Hiding struct members can add robustness, but doesn’t work for non-structs
  11. Summary • Interfaces can abstract different implementations of common behaviour

    • Can also be used shield against direct access to non-struct types (arrays, slices, etc)
  12. Summary • Some mechanisms exist for re-using ADT method implementation

    (e.g. anonymous fields) • But for now, good old "procedural abstraction" is not a bad idea.
  13. // Header file "api.h" struct Entity; extern struct Entity *

    open_entity(int id); extern int process_entity(struct Entity *info); extern void close_entity(struct Entity *info);