Skip to content

Commit 5530480

Browse files
committed
Functions should be at one level of abstraction
1 parent b8b382d commit 5530480

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

README.md

+68
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,74 @@ dateAddMonth(date, 1);
298298
```
299299
**[⬆ back to top](#table-of-contents)**
300300

301+
### Functions should only be one level of abstraction
302+
When you have more than one level of abstraction your function is usually
303+
doing too much. Splitting up functions leads to reusability and easier
304+
testing.
305+
306+
**Bad:**
307+
```javascript
308+
function parseBetterJSAlternative(code) {
309+
let REGEXES = [
310+
// ...
311+
];
312+
313+
let statements = code.split(' ');
314+
let tokens;
315+
REGEXES.forEach((REGEX) => {
316+
statements.forEach((statement) => {
317+
// ...
318+
})
319+
});
320+
321+
let ast;
322+
tokens.forEach((token) => {
323+
// lex...
324+
});
325+
326+
ast.forEach((node) => {
327+
// parse...
328+
})
329+
}
330+
```
331+
332+
**Good**:
333+
```javascript
334+
function tokenize() {
335+
let REGEXES = [
336+
// ...
337+
];
338+
339+
let statements = code.split(' ');
340+
let tokens;
341+
REGEXES.forEach((REGEX) => {
342+
statements.forEach((statement) => {
343+
// ...
344+
})
345+
});
346+
347+
return tokens;
348+
}
349+
350+
function lexer() {
351+
let ast;
352+
tokens.forEach((token) => {
353+
// lex...
354+
});
355+
356+
return ast;
357+
}
358+
359+
function parseBetterJSAlternative(code) {
360+
let tokens = tokenize(code);
361+
let ast = lexer(ast);
362+
ast.forEach((node) => {
363+
// parse...
364+
})
365+
}
366+
```
367+
**[⬆ back to top](#table-of-contents)**
368+
301369
### Remove duplicate code
302370
Never ever, ever, under any circumstance, have duplicate code. There's no reason
303371
for it and it's quite possibly the worst sin you can commit as a professional

0 commit comments

Comments
 (0)