首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >业务逻辑分离

业务逻辑分离
EN

Stack Overflow用户
提问于 2010-11-26 08:29:45
回答 4查看 570关注 0票数 1

我有一个customers类,它定义了属性和方法。目前,它包含与客户关联的任何类型任务的方法。例如,它包含一个方法"InsertOrUpdateCustomer“。此方法可以将新的客户记录插入数据库,也可以方便编辑现有的客户记录。

这个类还包含一些客户字段的验证方法。

我认为这不是一个更好的办法。我想把它弄成这样:

代码语言:javascript
复制
interface ICustomer
{
    string CustomerName;
    date FinancialYearStartDate;
    date FinancialYearEndDate;
    string TaxNo;
    string Address;
}

我想将这个接口实现到另一个类,比如Customers:

代码语言:javascript
复制
class Customers: ICustomer
{
    // Properties
    CustomerName { get; set; }
    FinancialYearStartDate { get; set; }
    FinancialYearEndDate  { get; set; }
    TaxNo { get; set; }
    Address { get; set; }

    // Constructor
}

我想知道:

  1. 在哪里添加插入或更新新客户的方法?我应该创建另一个类还是向上面的类添加方法?
  2. 用以上的方式打破我以前的单课对我是否有好处?接口在上面的代码中有什么好处?
  3. 我希望删除验证方法并使用验证框架。我是否需要创建一个不同的类"CustomerValidations“来进行验证,还是应该使用类本身?
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-11-26 08:39:55

  1. 对于插入和更新方法,我将使用CRUD方法(例如,存储库 )创建一个CRUD方法。
  2. 我看不出ICustomer接口的直接好处
  3. 当验证在业务实体之外时,我将使用这种方法;例如,在专用验证类中,或者在像spring.net验证这样的配置文件中。

总的来说,我认为每个类都有一个单一责任是个好主意,例如业务状态Customer、持久存储NHibernateCustomerRepository : ICustomerRepository和验证CustomerValidator

存储库的一个示例:

代码语言:javascript
复制
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);
  // ...
}

如您所见,这个接口的第一种方法对于大多数业务实体来说都是相似的,可以抽象为:

代码语言:javascript
复制
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);
}
票数 4
EN

Stack Overflow用户

发布于 2010-11-26 08:35:54

我的回答是:

  1. 我会将Insert方法放在包含ICustomers的类中(我想会有一个或多个)。至于更新,则取决于此方法的功能。如果您正在更新某些客户的内部字段/属性,则应该使用ICustomers;
  2. IMHO最大的好处之一是,依赖于客户的单元测试代码要容易得多,因为您可以轻松地模拟/存根它。
  3. 我会用这门课。
票数 2
EN

Stack Overflow用户

发布于 2010-11-26 08:35:11

像'InsertOrUpdateCustomer‘这样的动作通常是客户实体服务的一部分(在适配器模型中)(如您建议的那样,在另一个类中)。

思考这个问题的方法是:“谁有责任拯救客户?”

一种可能是将ICustomerValidator“注入”到保存方法中。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4283624

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档