简体   繁体   中英

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 ?

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€):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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