Replace Method with Method Object(以函數對象取代函數)

來源:互聯網
上載者:User

 

重構 6.9 節中 Replace Method with Method Object(以函數對象取代函數)

Replace Method with Method Object (以函數對象取代函數) 大家有沒有什麼心得!

例如下面的代碼:

TestMethod()方法內調用了 test1() test2()這2個私人方法時,

如果應用 Replace Method with Method Object,為保證程式的正確性,

必須將 test1() test2() 更改成 public method 才可以。

那麼基於這樣的更改,就暴露了test1() test() 方法。在這種情況下,有什麼好的建議呢?

 

 1 
 2 public class TestClass
 3     {
 4         private void test1() { }
 5         private void test2() { }
 6 
 7         public void TestMethod()
 8         {
 9             if (true)
10             {
11                 //若干方法
12                 test1();
13             }
14             else
15             {
16                 //若干方法
17                 test2();
18             }
19         }
20     }
21 
22 

 

   

至於使用了這個 Replace Method with Method Object 方法是因為當前類包含了上千行的代碼。

該類是一個程式的主表單。由於菜單很多,故有很多的事件代碼。當然了,我已經使用 partial class 將事件代碼全部分離到一個單獨的檔案中了。

但是該類還是包含了 500 多行的代碼。其中有2個方法各自都包含了大概70行左右的代碼量。

於是我使用了 Replace Method with Method Object,將這2個方法分離了出去。

關於這2個方法:

CheckLogin() 方法是驗證使用者的登入的。在該方法中:構造了LoginForm的一個對象,使用了匿名方法為該對象添加了按鈕的點擊事件。

ChangeUser() 方法更改登入使用者的。方法同上,區別在於對象按鈕的事件代碼的不同。

關於LoginForm類:

CheckLogin() && ChangeUser() 方法共用了 LoginForm 表單。所以在 LoginForm類的執行個體化方法中沒有添加按鈕的點擊事件。 

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.