Go for Classic OO

From Adam Colton
Revision as of 16:19, 11 August 2016 by Adamcolton (talk | contribs) (Created page with "== Key Difference == * Private is package wide * structs are concrete, interfaces are abstract * interfaces ONLY specify methods * embedding * using funcs to customize behavio...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Key Difference

  • Private is package wide
  • structs are concrete, interfaces are abstract
  • interfaces ONLY specify methods
  • embedding
  • using funcs to customize behavior
  • methods can be defined on any type

The Basics

At first structs seem very classic-object (COB) like. A struct has fields and you can define methods on it. The first difference you'll notice though is that the methods are not in the struct.

Packages

It's also important to talk about the role packages play in Go-OO. Anything starting with an uppercase is public, lowercase is private. But unlike COO, privates are package wide.

Interfaces

Interfaces must match

one gotcha is that you may run into - interfaces must exactly match.

 Name() fmt.Stringer
 // does not match
 Name() someStringStruct

Techniques

Privacy Tricks

Private abstract

Let's say you'll have 3 structs that will share some similarities, may just as simple as having a read-only ID. You can create a private struct with the necessary fields and embed that in the public structs. Externally, that struct is completely hidden, but the public methods and fields will be exposed.