Skip to content

Instantly share code, notes, and snippets.

@mnishiguchi
Created April 27, 2019 11:38
Show Gist options
  • Save mnishiguchi/fbb5ad3dcb71373ee10f137c9ba820b6 to your computer and use it in GitHub Desktop.
Save mnishiguchi/fbb5ad3dcb71373ee10f137c9ba820b6 to your computer and use it in GitHub Desktop.
RubyConf 2016 - Composition by James Dabbs

RubyConf 2016 - Composition by James Dabbs

Category Theory

  • study of composition
  • a collection of objects
  • functions between those objects
  • the means to compose functions
  • etc

Object Composition

  • a object holding a reference to one or more other objects that is collaborates with to fulfill its responsibilities.
  • has-a relationship (as opposed to inheritance's is-a)
  • composition over inheritance
  • f . g = f(g(x))

Guidelines for functional Ruby

  • Objects should have a defined collection of fields. An object's state should be expressible entirely in terms of those fields.
  • Fields should be set at initialization and then frozen. "Update" are performed by creating a new object.
  • Objects should respond to call to perform their (primary) responsibility.

Advantages of using composition

our objects:

  • have a clearly defined responsibility
  • have a predictable interface
  • are immutable
  • have injectable dependencies
  • are easy to configure and re-configure
  • are easy to test
  • are easy to mock in tests

componse method for callables

def call(sms)
  compose(
    :parse_message,
    :build_order,
    :validate_order,
    :record,
    :send_response
  ).call(sms)
end

def compose(*methods)
  ->(val) do
    result = val
    methods.each do |name|
      result = method(name).call(result)
    end
    result
  end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment