去除程式的壞味道 - 善用VS 2005的Refactor提升程式碼品質 文/沈炳宏 -----box----- 程式1 private void Form1_Load(object sender, EventArgs e) { int i, num, sum = 0; for (i = 1; i <= num; i++) { sum += i; } } -----box----- -----box----- 程式2 private void Form1_Load(object sender, EventArgs e) { int i, num, sum = 0; i = CalculateSum(num, ref sum); } private static int CalculateSum (int num, ref int sum) { int i; for (i = 1; i <= num; i++) { sum += i; } return i; } -----box----- -----box----- 程式3 private static void CalculateSum() { int i, num, sum = 0; for (i = 1; i <= num; i++) { sum += i; } } -----box----- -----box----- 程式4 class ProtoClassA { // 呼叫 'MethodB'. public void MethodB(int i, bool b) { } } class ProtoClassC { void D() { ProtoClassA MyClassA = new ProtoClassA(); // 呼叫 'MethodB'. MyClassA.MethodB(0, false); } } -----box----- -----box----- 程式5 class Square { public int width; public int height; } class MainClass { public static void Main() { Square mySquare = new Square(); mySquare.width = 110; mySquare.height = 150; Console.WriteLine("width = {0}", mySquare.width); Console.WriteLine("height = {0}", mySquare.height); } } -----box----- -----box----- 程式6 class Square { private int width; public int height; public int Width { get { return width; } set { width = value; } } } class MainClass { public static void Main() { Square mySquare = new Square(); mySquare.Width = 110; mySquare.height = 150; Console.WriteLine("width = {0}", mySquare.Width); Console.WriteLine("height = {0}", mySquare.height); } } -----box----- -----box----- 程式7 class ProtoA { public void MethodB(string s) { } } -----box----- -----box----- 程式8 class ProtoA : IProtoA { public void MethodB(string s) { } } -----box----- -----box----- 程式9 interface IProtoA { void MethodB(string s); } -----box----- -----box----- 程式10 class ProtoA { public static void MethodB() { int i = 5; } } class ProtoC { void MethodD() { ProtoA.MethodB(); } } -----box----- -----box----- 程式11 class ProtoA { public static void MethodB(int i) { } } class ProtoC { void MethodD() { ProtoA.MethodB(5); } } -----box----- -----box----- 程式12 class A { public A(string s, int i) { } } class B { void C() { A a = new A("a", 2); } } -----box----- -----box----- 程式13 class A { public A(int i) { } } class B { void C() { A a = new A(2); } } -----box----- -----box----- 程式14 class ImageRenderer { public void Render( Point topLeft, Point bottomRight, Graphics g){} public void Render(Graphics g, int x, int y) {} public void Render( Graphics g, Rectangle boundingBox) {} } -----box----- -----box----- 程式15 class ImageRenderer { public void Render( Graphics g, Point topLeft, Point bottomRight){} public void Render(Graphics g, int x, int y) {} public void Render( Graphics g, Rectangle boundingBox){} } -----box-----