2010-11-26 190 views
2

我有一個客戶類與屬性和方法定義。目前它包含與客戶關聯的任何類型任務的方法。例如,它包含一個方法「InsertOrUpdateCustomer」。該方法將新的客戶記錄插入到數據庫中,或者便於編輯現有的客戶記錄。分離業務邏輯

該類還包含一些客戶字段的驗證方法。

我認爲這不是一個更好的方法。我想有些突破這樣的:

interface ICustomer 
{ 
    string CustomerName; 
    date FinancialYearStartDate; 
    date FinancialYearEndDate; 
    string TaxNo; 
    string Address; 
} 

我想實現這個接口到另一個類,說客戶:

class Customers: ICustomer 
{ 
    // Properties 
    CustomerName { get; set; } 
    FinancialYearStartDate { get; set; } 
    FinancialYearEndDate { get; set; } 
    TaxNo { get; set; } 
    Address { get; set; } 

    // Constructor 
} 

我想知道:

  1. 在哪裏添加插入或更新新客戶的方法?我應該創建另一個類還是向上面的類添加方法?

  2. 用上面給出的方式打破我的舊單班是有益的或不是?上述代碼中界面有什麼優點?

  3. 我想刪除驗證方法並使用驗證框架來代替。我是否需要創建一個不同的「CustomerValidations」類,在那裏進行驗證,或者我應該使用上面的類本身?

回答

4
  1. 對於插入和更新方法,我會創建一個帶有CRUD方法的repository(例如,ICustomerRepository
  2. 我沒有看到ICustomer接口的直接好處
  3. 我會使用驗證在業務實體之外的方法;例如在專用的驗證類中,或者在像spring.net validation這樣的配置文件中。

總體而言,我認爲每個班級有single responsibility是個好主意 - 例如,業務狀態Customer,持久存儲NHibernateCustomerRepository : ICustomerRepository和驗證CustomerValidator

存儲庫的一個例子:

interface ICustomerRepository 
{ 
    // Get by id 
    Customer Get(int id); 
    void Delete(Customer customer); 
    IList<Customer> GetAll(); 
    // creates a new instance in datastore 
    // returns the persistent identifier 
    int Save(Customer customer); 
    // updates if customer exists, 
    // creates if not 
    // returns persistent identifier 
    int SaveOrUpdate(Customer customer); 
    // updates customer 
    void Update(Customer customer); 

    // specific queries 
    IList<Customer> GetAllWithinFiscalYear(DateTime year); 
    // ... 
} 

正如你所看到的,這個接口的第一個方法對於大多數企業實體相似,可以抽象爲:

interface IRepository<TId, TEntity> 
{ 
    // Get by id 
    TEntity Get(TId id); 
    void Delete(TEntity entity); 
    IList<TEntity> GetAll(); 
    // creates a new instance in datastore 
    // returns the persistent identifier 
    TId Save(TEntity entity); 
    // updates if customer exists, 
    // creates if not 
    // returns persistent identiefier 
    TId SaveOrUpdate(TEntity entity); 
    // updates customer 
    void Update(TEntity entity); 
} 

interface ICustomerRepository : IRepository<int, Customer> 
{ 
    // specific queries 
    IList<Customer> GetAllWithinFiscalYear(DateTime year); 
} 
1

的動作,如「InsertOrUpdateCustomer」通常是一個客戶實體服務的一部分(適配器模式)(在另一類即你的建議)

想它的方式是:「誰的責任是挽救客戶?「

一種可能性是將'ICustomerValidator'注入到Save方法中。

2

我的答案:

  1. 我把插入法將包含ICustomers類(我想會有一個或多個)。至於更新,這取決於這個方法的作用。如果您正在更新某些客戶的內部字段/屬性,則應與ICustomers一起進行;

  2. 恕我直言,最大的好處之一就是單元測試代碼依賴於客戶,因爲您可以輕鬆地模擬/存根,因此更容易。

  3. 我會使用類本身。

+1

哪裏是關注的分離? – 2010-11-26 08:36:32

+0

我請你原諒,但我沒有得到這個問題... – Simone 2010-11-26 08:42:23

0

介紹基本上是數據容器的類的接口很少有益。相反,您可能需要分別創建兩個具有數據庫持久性和驗證角色的類。有一個接口可能會讓您有機會使這些類可以互換用於測試或不同的存儲/驗證策略。