步步为营.NET代码重构学习笔记十三
一、Replace Exception with Test(以测试取代异常)
动机(Motivation)
面对一个[调用者可预先加以检查]的条件,你抛出了一个异常。修改调用者,使它在调用函数之前先做检查。
示例
01 private Dictionary<int, string> _values;
02
03 public double GetValueForPeriod(int periodNumber)
04 {
05 try
06 {
07 return _values[periodNumber];
08 }
09 catch
10 {
11 return 0;
12 }
13 }
改为
view sourceprint?1 private Dictionary<int, string> _values;
2
3 public double GetValueForPeriod(int periodNumber)
4 {
5 if (_values.ContainsKey(periodNumber))
6 return _values[periodNumber];
7 return 0;
8 }
二、Pull Up Field(值域上移)
动机(Motivation)
两个subclasses拥有相同的值域,将此一值域移至superclass。
示例
01 public abstract class Emplayee
02 {
03
04 }
05
06 public class Salesman : Emplayee
07 {
08 private string _name;
09
10 public string Name
11 {
12 get { return _name; }
13 set { _name = value; }
14 }
15 }
16
17 public class Engineer : Emplayee
18 {
19 private string _name;
20
21 public string Name
22 {
23 get { return _name; }
24 set { _name = value; }
25 }
26 }
改为
01 public abstract class Emplayee
02 {
03 private string _name;
04
05 public string Name
06 {
07 get { return _name; }
08 set { _name = value; }
09 }
10 }
11
12 public class Salesman : Emplayee
13 {
14
15 }
16
17 public class Engineer : Emplayee
18 {
19
20 }
三、Pull Up Method(函数上移)
动机(Motivation)
有些函数,在各个subclass中产生完全相同的结果。将该函数移至superclass。
示例
01 public abstract class Emplayee
02 {
03
04 }
05
06 public class Salesman : Emplayee
07 {
08 public string GetName()
09 {
10 return "spring yang";
11 }
12 }
13
14 public class Engineer : Emplayee
15 {
16 public string GetName()
17 {
18 return "spring yang";
19 }
20 }
改为
01 public abstract class Emplayee
02 {
03 public string GetName()
04 {
05 return "spring yang";
06 }
07 }
08
09 public class Salesman : Emplayee
10 {
11 }
12
13 public class Engineer : Emplayee
14 {
15 }
四、Pull Up Constructor Body(构造函数本体上移)
动机(Motivation)
在各个subclass中拥有一些构造函数,它们的本体代码几乎一致,在base中新建一个构造函数,并在subclass构造函数中调用它。
示例
01 public abstract class Emplayee
02 {
03 private string _ID;
04 private string _name;
05
06 public string ID
07 {
08 get { return _ID; }
09 set { _ID = value; }
10 }
11
12 public string Name
13 {
14 get { return _name; }
15 set { _name = value; }
16 }
17 }
18
19 public class Salesman : Emplayee
20 {
21 public Salesman(string id, string name)
22 {
23 ID = id;
24 Name = name;
25 }
26 }
改为
01 public abstract class Emplayee
02 {
03 private string _ID;
04 private string _name;
05
06 public string ID
07 {
08 get { return _ID; }
09 set { _ID = value; }
10 }
11
12 public string Name
13 {
14 get { return _name; }
15 set { _name = value; }
16 }
17
18 public Emplayee(string id, string name)
19 {
20 _ID = id;
21 _name = name;
22 }
23 }
24
25 public class Salesman : Emplayee
26 {
27
补充:Web开发 , ASP.Net ,