简体   繁体   English

编辑现有对象应该在存储库层还是在服务中完成?

[英]Editing of an existing object should be done in repository layer or in service?

For example if I have a User that has debt. 例如,如果我有一个有债务的用户。 I want to change his debt. 我想改变他的债务。 Should I do it in UserRepository or in service for example BuyingService by getting an object, editing it and saving it ? 我应该通过获取对象,编辑并保存对象,在UserRepository或服务中执行此操作(例如BuyingService)吗?

You should leave the responsibility of mutating an object to that same object and use the repository to retrieve this object. 您应该负责将对象变更为同一个对象,并使用存储库来检索此对象。

Example situation: 示例情况:

class User {
 private int debt; // debt in cents
 private string name;

 // getters

 public void makePayment(int cents){
  debt -= cents;
 }
}

class UserRepository {
 public User GetUserByName(string name){
  // Get appropriate user from database
 }
}

Usage (Jack pays 10€): 用法(杰克支付10欧元):

userRepository.GetUserByName("Jack").makePayment(1000);

Keep in mind that this is just an example approach. 请记住,这只是一个示例方法。 There is not one set way in programming to achieve something, you could very well do this entirely different. 在编程中没有一套方法可以实现某些目标,你可以完全不同地做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM