Skip to content

Instantly share code, notes, and snippets.

@don-smith
Created October 15, 2016 23:51
Show Gist options
  • Select an option

  • Save don-smith/f8af54042cdafc5e95c59e33fa349427 to your computer and use it in GitHub Desktop.

Select an option

Save don-smith/f8af54042cdafc5e95c59e33fa349427 to your computer and use it in GitHub Desktop.
// constructor function implementation
function Test (args) {
// explicit internal state without using `this`
const state = {
op: args.op,
missing: args.missing
}
return { // explicit return
// explicit binding of function
// parameters with internal state
// or only whatever it needs
go: go.bind(null, state)
}
}
// functions defined separately
// can't (and shouldn't) alter object state
// should only act on inputs and return
function go (options) {
return `${options.op} without: ${options.missing}`
}
// during normal use
const options = {op: 'running', missing: 'this'}
const test = Test(options) // `new` is optional
console.log('Normal use and', test.go())
// testing the function directly
const testOptions = {op: 'Testing', missing: 'object'}
const expected = 'Testing without: object'
const actual = go(testOptions)
console.log(actual)
console.log('Test passes:', actual === expected)
@don-smith
Copy link
Copy Markdown
Author

don-smith commented Oct 16, 2016

This is just some early thinking based on https://github.com/hoodiehq/hoodie/blob/master/docs/developers/CODING_STYLE.rst#avoid-this-and-object-oriented-coding-styles. I find I always need good object creation patterns, but almost never need inheritance. I also need an easy way to test functionality and an am not precious about encapsulation. I could use underscore prefixes (e.g _go(testOptions)) if I need to set expectation about is intended to be private. I also like how this encourages immutable objects and pure functions. I haven't yet explored the impact this approach has on inheritance, but this feels useful so far.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment