Rules
- no side effects (function can't rely on anything not provided to it)
- inputs and outputs
In Practice
- Nested functions are always an indication of complexity
Creates Functions that are
- Easy to read
- Easy to reuse
- Easy to test
- Easy to change
Examples (all pulled from code I reviewed at PaperG just simplified and anonymized):
Reusability
// add foo to bar
var foo = 1;
var bar = 2;
function add (number_1) {
return number_1 + bar;
}
// add foo to bar
var foo = 1;
var bar = 2;
function add (number_1, number_2) {
return number_1 + number_2;
}
Testability
var foo = [1, 2, 3, 4, 5];
_.each(function (num) {
num++;
});
var foo = [1, 2, 3, 4, 5];
function add_one (num) {
return num + 1;
}
var bar = foo.map(add_one);
$scope.toggleView = function($event, grid) {
if (grid) {
stopCropping();
}
setGrid(grid);
$event.stopPropagation();
};
function toggleView ($event, grid) {
// not entirely sure how this code works but....
var newView = _.cloneDeep(oldview);