2014-03-04 29 views
-3

比方說,我有一個網頁(建立在MVC 4使用VB.Net),顯示用戶可以通過點擊編輯鏈接編輯的數據。該鏈接將通過傳遞相關數據字段的id路由至Edit函數。良好的編程習慣:在另一個函數調用的參數列表中使用函數調用?

要顯示我的編輯頁面,我將抓取數據,將其映射到模型,並將其傳遞給視圖。我們將調用我的映射函數Map2Model,它接受實體框架模型&返回模型和數據訪問函數GetData,它返回實體框架模型。 GetData接受數據的id,以及userid。我們將使用SimpleMembership進行用戶驗證。它是被認爲不好的做法,執行以下操作(調用另一個函數調用的參數列表中的函數:

Function Edit(ByVal id as Integer) as ActionResult 
    Dim Model2Edit = Map2Model(GetData(id, WebSecurity.GetUserId(User.Identity.Name))) 
    Return View(Model2Edit) 
End Function 

VS.(第一聲明變量)

Function Edit(ByVal id as Integer) as ActionResult 
    Dim TheData as New EntityModel 
    Dim UserID as Integer 
    Dim Model2Edit as New Model 

    UserID = WebSecurity.GetUserId(User.Identity.Name) 
    TheData = GetData(id, UserID) 
    Model2Edit = Map2Model(TheData) 

    Return View(Model2Edit) 
End Function 

在C#:

public ActionResult Edit(int id) 
    { 
    dynamic Model2Edit = Map2Model(GetData(id, WebSecurity.GetUserId(User.Identity.Name))); 
    return View(Model2Edit); 
    } 

VS.

public ActionResult Edit(int id) 
{ 
    EntityModel TheData = new EntityModel(); 
    int UserID = 0; 
    Model Model2Edit = new Model(); 

    UserID = WebSecurity.GetUserId(User.Identity.Name); 
    TheData = GetData(id, UserID); 
    Model2Edit = Map2Model(TheData); 

    return View(Model2Edit); 
} 

除了這是否是不好的做法,我希望我的代碼可讀。我覺得應該使描述性的功能應該易於遵循。

編輯修正我的頭銜

EDIT 2進一步細化的問題。

編輯3新增的C#代碼

+1

我不明白你的問題是什麼。你問一個函數調用另一個函數是否是好習慣?如果是的話,答案當然是......你不是一直這麼做嗎? –

+0

是否要求用另一種方法調用方法是不好的做法?當然這不是不好的做法!如何在不調用方法的情況下編程任何東西! – Liam

+2

而不是什麼替代? – Jonesopolis

回答

5

我假設你確切的問題是:

是它認爲不好的做法,另一個函數調用的參數列表中調用一個函數:

         V---------------------------------------V 
Dim Model2Edit = Map2Model(GetData(id, WebSecurity.GetUserId(User.Identity.Name))) 

不,因爲這是唯一的地方,你使用的值是完全正確的。如果你曾經重用過這個值,那麼顯然最好保留引用而不是再次調用函數。

其他需要考慮的因素:

  • 它使函數調用會不必要長時間?
  • 這個調用是否會拋出你想要處理的異常?
  • 這個調用是否返回了一個你想包裝在using塊中的一次性對象?

如果你想要一個真正的試金石測試,讓其他人看看代碼,看看他們是否很難理解目的是什麼。

+1

ahhh,這就是問題所在...... – Liam

+3

解密問題的好工作 – Jonesopolis

+0

謝謝 - 我修正了標題。 – merlot

1

開始通過使一些變量:

Dim name = User.Identity.Name 
Dim User = WebSecurity.GetUserId(name) 
Dim Data = GetData(id, User) 
Dim Model2Edit = Map2Model(Data) 
Return View(Model2Edit) 

然後確定你的程序的其他部分使用喜歡把自己的用戶部分,並開始重構:

Dim User = GetUser() -> introduce a new function 
Dim Data = GetData(id, User) 
Dim Model2Edit = Map2Model(Data) 
Return View(Model2Edit) 

這僅僅是在重構開始並使其更具可讀性。

相關問題