Git Product home page Git Product logo

options's Introduction

options

Use Case

You have a constructor-type func which accepts optional funcs as parameters. Rob Pike and Dave Cheney have discussed this in 2014 and 2016, respectively.

func SpecificThingOptionFunc func(st *SpecificThing) error

func SetHost(host string) error {
  return func(st *SpecificThing) error {
    st.host = host
    return nil
  }
}

type SpecificThing struct {
  host string
}

func NewSpecificThing(options ...SpecificThingOptionFunc) *SpecificThing {
  st := &SpecificThing{}
  for o := range options {
    o(st)
  }
  return st
}

func main() {
  st := NewSpecificThing(SetHost("example.com"))
  // ...
}

If a program has many specific things, it may have some common things, using struct cmoposition.

type CommonThing struct {
  loggingLevel int
}

type SpecificThing struct {
  CommonThing
  host string
}

Continue the options func pattern, CommonThing can also have option funcs.

func CommonThingOptionFunc func(ct *CommonThing) error

func SetLoggingLevel(loggingLevel int) error {
  return func(ct *CommonThing) error {
    ct.loggingLevel = loggingLevel
    return nil
  }
}

The problem comes when the SpecificThing constructor wants to apply option to its CommontThing. There are a couple of common patterns that can address this.

Multiple sets of options

A constructor may accept arrays of options of different types by dropping the vardiac syntax:

func NewSpecificThing(ct CommonThing, ctOptions []CommonThingOptionFunc, stOptions []SpecificThingOptionFunc) {
  ct := CommonThing {}
  for o := range ctOptions {
    o(ct)
  }
  st := &SpecificThing {
    CommonThing: ct,
  }
  for o := range stOptions {
    o(st)
  }
  return st
}

This rapidly becomes inellegant and unweildy as the number of embedded structures with options grows. For example, if CommonThing also embeds another struct, and that struct embeds one, etc., the argument list rapidly grows out of control.

Dependency Injection

A constructor may require that all of its constituant parts may already exist at the time of construction:

func NewSpecificThing(ct CommonThing, options ...SpecificThingOptionFunc) {
  st := &SpecificThing {
    CommonThing: ct,
  }
  for o := range options {
    o(st)
  }
  return st
}

This pattern should scale more elegantly. However, this looks a little like dependency injection, which is not appropriate for every project.

Motivation

The goals of this project are to allow a single options func to be applicable across many embedded structs.

Usage

options github.com/object88/hoarding:Options,Suboptions github.com/object88/hoarding/internal:Options

options's People

Contributors

object88 avatar

Watchers

 avatar

options's Issues

Do not attempt to recreate methods

Starting with code...

package foo

type FooOptions struct {
  a string
}

func (fo *FooOptions) SetA(a string) {
  // etc.
}

The generator should not attempt to create a new SetA method.

Annotation to specify target struct

The current implementation accepts a command-line argument to specify a path to a package and a target struct:

options ./example:FooStruct

An alternate might be to only supply the path, and allow an comment-based directive to define the target struct:

options ./example

With code:

package foo

//options:generate
type FooOptions struct {
  a string
}

Note that this goes contrary to the idea of using tags to instrument a struct for use with options. A tag cannot be applied to a struct, unfortunately. This idea may need to be abandoned.

Determine tag structure

Tags are useful ways to add extra information to a field in a struct, although not the struct itself, to facilitate operations on the field. See gophercon 2015 talk for interesting examples and idea.

In terms of options, we can leverage tags on fields to change how the generated option func is named, its privacy, or whether it should be ignored.

The exact semantics of the tag need to be determined, and validated so that they will pass go vet.

Further notes:
https://golang.org/ref/spec#Tag
https://github.com/golang/go/wiki/Well-known-struct-tags
https://medium.com/golangspec/tags-in-golang-3e5db0b8ef3e
https://stackoverflow.com/a/30889373/1301815

Comment-based directive to ignore

By default, option funcs are always generated. Add comment-based directive to allow for ignoring a field:

Example:

package foo

type FooOptions struct {
  //options:ignore
  a string

  b int
}

This should generate an OptionFunc for b, but not a.

The exact directive semantics are TBD, and will depend on the complete set of functionality to be baked into this tool.

Comment-based directive to set specific `OptionFunc` name

Given code:

package foo

type FooOptions struct {
  //options:name AssignA
  a string
}

Generate an OptionFunc with a different name:

func (fo *FooOption) AssignA(a string) options.Option {
  // etc
}

The exact directive semantics are TBD, and will depend on the complete set of functionality to be baked into this tool.

Test nested struct

package foo

type CommonOptions struct {
  debug bool
}

type FooOptions struct {
  CommonOptions
  a string
}

Also, consider nested struct from another package. Document limitations. For example, what is the expected behavior for an options struct that is composed with via two different paths:

package main

import (
	"fmt"
)

type A struct {
  a string
}

type B struct {
  A
  b string
}

type C struct {
  A
  c string
}

type D struct {
  B
  C
  d string
}

func main() {
  d := D{}
  d.B.a = "aaaaa"
  fmt.Printf("d: %#v\n", d)
}

Gracefully halt if target struct already has `Apply` func

Given the code...

type FooOptions struct {
  a string
}

func (fo *Foo) Apply() {}

Do not attempt to generate code. Doing so will result in the FooOptions struct having two implementations of an Apply method, which is illegal code.

Adjacently, consider whether the options.Optioner func Apply should have a different name.

Test with non-basic types

Go has a set of basic types (int, string, bool, etc). In addition, there are pointers (*int, *string, *bool`), arrays, maps, structs, pointers to structs, funcs, etc.. In the spirit of completeness, these should be explicitly tested.

Comment-based directive to make private

By default, option funcs are public. Add comment-based directive to allow for generation of a private option func:

Example:

package foo

type FooOptions struct {
  //options:private
  a string
}

Generates:

func (fo *FooOptions) setA(a string) options.Option {
  // etc.
}

The exact directive semantics are TBD, and will depend on the complete set of functionality to be baked into this tool.

Test with `go:generate`

Create test to ensure proper functionality with go:generate

package foo

//go:generate options .:FooOptions

type FooOptions struct {
  a string
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.