Skip to content

Latest commit

 

History

History
75 lines (49 loc) · 2.5 KB

07-OO.md

File metadata and controls

75 lines (49 loc) · 2.5 KB

Object Oriented Programming

https://go.dev/doc/faq#Is_Go_an_object-oriented_language

Yes and no. Although Go has types and methods and allows an object-oriented style of programming, there is no type hierarchy. The concept of “interface” in Go provides a different approach that we believe is easy to use and in some ways more general.

There are also ways to embed types in other types to provide something analogous—but not identical—to subclassing. Moreover, methods in Go are more general than in C++ or Java: they can be defined for any sort of data, even built-in types such as plain, “unboxed” integers. They are not restricted to structs (classes).

Contructors

Does Go support function overloading?

No it does not.

When faced with the decision of providing a constructor for a type, these are the most common approaches - using a hypothetical Store implemented in a package store:

Constructor variants

  • store.New(...) Store
  • store.New(...) (Store, error)
  • store.NewStore(...) (Store, error)
  • store.NewCapacity(...) ...
  • store.NewCapacityTimeout(...) ...

This is fine for simple case, few variants, but unwieldy for many options.

Using separate options

Define a separate Opts struct with the options you want to pass to the constructor.

  • store.New(opts Opts) (Store, error)

In the wild:

reader, err := cli.ImagePull(ctx, "docker.io/library/alpine", types.ImagePullOptions{})
if err != nil {
    panic(err)
}
io.Copy(os.Stdout, reader)

Functional Options Pattern

More: https://dave.cheney.net/2014/10/17/functional-options-for-friendly-apis

Composition over inheritance

The bigger the interface, the weaker the abstraction.

There are no type hierarchies in Go.

Example of providing a varienty of implementations using interfaces:

Notes:

  • image.Image is an interface, containing three methods, which themselves can be interfaces
  • there are a couple of implementation in subdirectories, e.g. jpg, png, ...