@@ -307,31 +307,34 @@ addMonthToDate(1, $date);
307
307
** [ ⬆ back to top] ( #table-of-contents ) **
308
308
309
309
### Functions should only be one level of abstraction
310
+
310
311
When you have more than one level of abstraction your function is usually
311
312
doing too much. Splitting up functions leads to reusability and easier
312
313
testing.
313
314
314
315
** Bad:**
316
+
315
317
``` php
316
- function parseBetterJSAlternative($code) {
318
+ function parseBetterJSAlternative($code)
319
+ {
317
320
$regexes = [
318
321
// ...
319
322
];
320
323
321
324
$statements = split(' ', $code);
322
325
$tokens = [];
323
- foreach($regexes as $regex) {
324
- foreach($statements as $statement) {
326
+ foreach ($regexes as $regex) {
327
+ foreach ($statements as $statement) {
325
328
// ...
326
329
}
327
330
}
328
331
329
332
$ast = [];
330
- foreach($tokens as $token) {
333
+ foreach ($tokens as $token) {
331
334
// lex...
332
335
}
333
336
334
- foreach($ast as $node) {
337
+ foreach ($ast as $node) {
335
338
// parse...
336
339
}
337
340
}
@@ -340,39 +343,43 @@ function parseBetterJSAlternative($code) {
340
343
** Good:**
341
344
342
345
``` php
343
- function tokenize($code) {
346
+ function tokenize($code)
347
+ {
344
348
$regexes = [
345
349
// ...
346
350
];
347
351
348
352
$statements = split(' ', $code);
349
353
$tokens = [];
350
- foreach($regexes as $regex) {
351
- foreach($statements as $statement) {
354
+ foreach ($regexes as $regex) {
355
+ foreach ($statements as $statement) {
352
356
$tokens[] = /* ... */;
353
- });
354
- });
357
+ }
358
+ }
355
359
356
360
return $tokens;
357
361
}
358
362
359
- function lexer($tokens) {
363
+ function lexer($tokens)
364
+ {
360
365
$ast = [];
361
- foreach($tokens as $token) {
366
+ foreach ($tokens as $token) {
362
367
$ast[] = /* ... */;
363
- });
368
+ }
364
369
365
370
return $ast;
366
371
}
367
372
368
- function parseBetterJSAlternative($code) {
373
+ function parseBetterJSAlternative($code)
374
+ {
369
375
$tokens = tokenize($code);
370
376
$ast = lexer($tokens);
371
- foreach($ast as $node) {
377
+ foreach ($ast as $node) {
372
378
// parse...
373
- });
379
+ }
374
380
}
375
381
```
382
+
376
383
** [ ⬆ back to top] ( #table-of-contents ) **
377
384
378
385
### Remove duplicate code
0 commit comments