Help us shape the future of Go! Take the 2026 Go Developer Survey

chainable

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 25, 2019 License: MIT Imports: 2 Imported by: 0

README

Go-chainable

Build Status Maintainability Test Coverage GoDoc

Provides an easy and convenient way of chaining function calls in Golang, with support to argument's feedback and error-handling

Requirements

  • Go 1.9 or later

Installation

go get github.com/mauricioklein/go-chainable

Basics

It's common to find Go programs similar to the one below:

x, err := sum2(2)
if err != nil {
    return 0, err
}

y, err = mul2(x)
if err != nil {
    return 0, err
}

z, err = div2(y)
if err != nil {
    return 0, err
}

return z, nil

Error handling can make the codebase messy. At the same time, chaining function calls can obfuscate errors and cascading calls can increase the cognitive complexity.

Elixir, F# and other languages solve this problem with the support to pipes, but Golang hasn't such feature.

Chainable provides a clearer way to chain function calls, using the output of the previous function as the input of the next one.

The example above could be re-written using Chainable as follow:

import (chainable "github.com/mauricioklein/go-chainable")

res, err := chainable.New().
    From(2).
    Chain(
        sum2,
        mul2,
        div2,
    ).
    Unwrap()

// "Unwrap" returns the result as a slice of Argument, matching the return values
// of the last function. So, we just need to cast them to the correct type
z := res[0].(int)

Another advantage is that Chainable automatically handle errors in a chain.

Thus, if one of the methods returns an error as the last argument, the chain is broken and the error is returned by the "Unwrap" method:

raiseError := func ()      (int, error) { return 0, errors.New("generic error") }
plus2      := func (x int)              { return x + 2 }

chainable.New().
    Chain(raiseError). // breakes the chain
    Chain(plus2).      // never called
    Unwrap()           // returns nil, "a generic error"

If automatic error handling isn't desired (i.e. the error should be chained along with the other arguments), the method "ChainDummy" should be used instead of "Chain" (pay attention that the next function in the chain must be able to receive the error generated by the previous one):

raiseError    := func ()               (int, error) { return 2, errors.New("generic error") }
plus2AndError := func (x int, e error) (int)        { return x + 2 }

chainable.New().
    ChainDummy(raiseError).
    Chain(plus2AndError).
    Unwrap() // returns []Argument{4}, nil

"Chain" and "DummyChain" methods are variadics, and can be used in conjunction:

chainable.New().
    Chain(f1).       // error handling enabled for f1
    ChainDummy(f2).  // error handling disabled for f2
    Chain(f3, f4).   // error handling enabled for f3 and f4
    Unwrap()

Finally, to reset a chain and make it ready to be reused, just call the method "Reset":

chain := chainable.New()

// ... use of chain

chain.Reset()

Contributing

  1. Fork it
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create new Pull Request

Documentation

Overview

Package chainable provides an easy and convenient way of chaining function calls in Golang.

Basics

It's common to find Go programs similar to the one below:

x, err := sum2(2)
if err != nil {
	return 0, err
}

y, err = mul2(x)
if err != nil {
	return 0, err
}

z, err = div2(y)
if err != nil {
	return 0, err
}

return z, nil

Error handling can make the codebase messy. At the same time, chaining function calls can obfuscate errors and cascading calls can increase the cognitive complexity.

Elixir, F# and other languages solve this problem with the support to pipes, but Golang hasn't such feature.

Chainable provides a clearer way to chain function calls, using the output of the previous function as the input of the next one. The example above could be re-written using Chainable as follow:

import (chainable "github.com/mauricioklein/go-chainable")

res, err := chainable.New().
	From(2).
	Chain(
		sum2,
		mul2,
		div2,
	).
	Unwrap()

// "Unwrap" returns the result as a slice of Argument, matching the return values
// of the last function. So, we just need to cast them to the correct type
z := res[0].(int)

Another advantage is that Chainable automatically handle errors in a chain. Thus, if one of the methods returns an error as the last argument, the chain is broken and the error is returned by the "Unwrap" method:

raiseError := func ()      (int, error) { return 0, errors.New("generic error") }
plus2      := func (x int)              { return x + 2 }

chainable.New().
	Chain(raiseError). // breakes the chain
	Chain(plus2).      // never called
	Unwrap()           // returns nil, "a generic error"

If automatic error handling isn't desired (i.e. the error should be chained along with the other arguments), the method "ChainDummy" should be used instead of "Chain". Pay attention that the next function in the chain must be able to receive the error generated by the previous one:

raiseError    := func ()               (int, error) { return 2, errors.New("generic error") }
plus2AndError := func (x int, e error) (int)        { return x + 2 }

chainable.New().
	ChainDummy(raiseError).
	Chain(plus2AndError).
	Unwrap() // returns []Argument{4}, nil

"Chain" and "DummyChain" methods are variadics, and can be used in conjunction:

chainable.New().
	Chain(f1).       // error handling enabled for f1
	ChainDummy(f2).  // error handling disabled for f2
	Chain(f3, f4).   // error handling enabled for f3 and f4
	Unwrap()

Finally, to reset a chain and make it ready to be reused, just call the method "Reset":

chain := chainable.New()

... use of chain

chain.Reset()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Argument

type Argument interface{}

Argument defines an argument provided to the functions in a chain

type Chainable

type Chainable struct {
	// contains filtered or unexported fields
}

Chainable defines the chain logic.

func New

func New() *Chainable

New instantiate a new Chainable instance

func (*Chainable) Chain

func (c *Chainable) Chain(funcs ...Function) *Chainable

Chain appends a new function to the chain, with error handling enabled

func (*Chainable) ChainDummy

func (c *Chainable) ChainDummy(funcs ...Function) *Chainable

ChainDummy appends a new function to the chain, with error handling disabled

func (*Chainable) From

func (c *Chainable) From(args ...Argument) *Chainable

From defines the arguments provided to the first function in a chain

func (*Chainable) Reset

func (c *Chainable) Reset() *Chainable

Reset cleanups a chain, removing all the links and initial values

func (*Chainable) Unwrap

func (c *Chainable) Unwrap() ([]Argument, error)

Unwrap process the chain. It returns a []Argument with the arguments returned by the last function in the chain (or nil, if the chain is broken) and an error, returned by any of the functions in the chain with error-handling enabled (or nil, if success)

type Function

type Function interface{}

Function defines a function added to the chain

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL