@@ -372,3 +372,97 @@ class Account{
372
372
}
373
373
```
374
374
375
+ ** 重构后**
376
+
377
+ ``` java
378
+ class Gamma {
379
+ private final Account _account;
380
+ private int inputVal;
381
+ private int quantityVal;
382
+ private int yearToDate;
383
+ private int importValue1;
384
+ private int importValue2;
385
+ private int importValue3;
386
+ Gamma (Account source ,int inputValArg ,int quantityArg ,int yearToDateArg ){impo
387
+ _account= source;
388
+ inputVal = inputValArg;
389
+ quantityVal= quantityArg;
390
+ yearToDate = yearToDateArg;
391
+
392
+ }
393
+ int commpute (){
394
+ importantValue1 = (inputVal* quantity)+ _account. delta();
395
+ importantValue2 = (inputVal* yearToDate)+ 100 ;
396
+ importantThing()
397
+ int importantValue3= importantValue2* 7 ;
398
+ // and so on
399
+ return importantValue3 - 2 * importantValue1;
400
+ }
401
+ }
402
+ int gamma(int inputVal,int quantity,int yearToDate){
403
+ return new Gamma (this ,inputVal,quantity,yearToDate). commpute();
404
+ }
405
+ void importantThing(){
406
+ if ((yearToDate- importantValue1)> 100 ){
407
+ importantValue2-= 20 ;
408
+ }
409
+ }
410
+ ```
411
+
412
+ ##### 6.9 Substitute Algorithm(替换算法)
413
+
414
+ 你想要把某个算法替换成另一个更清晰的算法。
415
+
416
+ ** 将函数本体替换为另一个算法。**
417
+
418
+ ``` java
419
+ String foundPerson(String [] people){
420
+ for (int i= 0 ;i< people. length;i++ ){
421
+ if (people[i]. euqals(" Don" )){
422
+ return " Don" ;
423
+ }
424
+ if (people[i]. equals(" John" )){
425
+ return " John" ;
426
+ }
427
+ if (people[i]. equals(" Kent" )){
428
+ return " kent" ;
429
+ }
430
+ }
431
+ return " " ;
432
+ }
433
+ ```
434
+
435
+
436
+
437
+ ** 重构后**
438
+
439
+ ``` java
440
+ String foundPerson(String [] people){
441
+ List candidates = Arrays . asList(new String []{" Don" ," John" ," kent" });
442
+ for (int i= 0 ;i< people. length;i++ ){
443
+ if (candidates. contains(people[i])){
444
+ return people[i];
445
+ }
446
+ }
447
+ return " " ;
448
+ }
449
+ ```
450
+
451
+
452
+
453
+ ** 动机**
454
+
455
+ - 重构可以把一些复杂东西简单化,但有时必须装饰断腕,删掉整个算法,代之简单算法。
456
+ - 使用这项重构手法之前,先确定自己已经尽可能分解了原先函数。
457
+
458
+ ** 做法**
459
+
460
+ - 准备好另一个(替换用)算法,让它通过编译。
461
+
462
+ - 针对现有测试,执行上述的新算法。如果结果与原本结果相同,重构结束。
463
+
464
+ - 入股屙屎结果不同于原先,在测试和调试过程中,以旧算法为比较参照标准。
465
+
466
+ > 对于每个测试用例,分别以新旧算法运行,并观察两者结果是否相同。这可帮助你看到哪一个测试用例出现麻烦,以及出现了怎么的麻烦。
467
+
468
+
0 commit comments