Created
October 15, 2016 23:51
-
-
Save don-smith/f8af54042cdafc5e95c59e33fa349427 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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) |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.