What would you name this CRUD class?

MrDustpan picture MrDustpan · May 8, 2009 · Viewed 7.6k times · Source

Trying to avoid the SomethingManager trap here...

Let's say I'm going to write a User editor which will allow administrators to create users in the system. Pretty basic functionality - view a list of existing users, create a new user, update an existing user, delete a user.

Let us also say that I decide to write a "business" class to handle these basic CRUD operations. This is probably what the interface would look like:

public interface ISomeUsefulName
{
    IList<User> FetchUsers();
    User FetchUser(int userId);
    bool SaveUser(User user);
    bool DeleteUser(int userId);
}

Inside the SaveUser() method, for example, I would validate the data (using a different class) and then actually save the data to the database (again using another class).

My question is, what should I name this class? Is this class doing too much and therefore I should split it into multiple classes?

Answer

ruslander picture ruslander · May 8, 2009

Naming is difficult if is not respected SRP :) But members naming is often misused.

In your case I'll do something like this:

  • the responsibility of implementation is to cover specified contract of persistence
  • "who" is under fire

Thinks without voice - persistence is done for user and a relevant name can be IUserRepository - methods are not more than for CRUD - because of the fact that the IUserRepository is for user, is not necessary to have UserSave, UserUpdate because it brakes the generic usage manner

The Magic Is Here ... just do this:

public interface IRepository<TYPE, KEY>{
  IList<TYPE> GetAll(KEY key);
  TYPE GetById(KEY key);
  void Save(TYPE obj);
  void Update(TYPE obj);
  void Delete(Key key);
}

Is it difficult ? What to do with a custom one?

public interface IUserRepository : IRepository<User, int>
{
   IList<User> GetAllMyFavorites(ICriteria crit);
   IList<Events> GetHistoryByUser(User user);   
}

In the code using an IoC container you can do easily

public UserController {
  private _userRepository = null;
  private _eventsRepository = null;

  public UserController(IUserRepository userRepository, 
  IRepository<Events,int> eventsRepository) 
  // if you are doing here just CRUD use the generic signature
  {
    _userRepository = userRepository;
    _eventsRepository = eventsRepository;
  }

  public MarkItAsGoldPartener(int userId){
     var user = userRepository.GetById(userId);
     user.PartnerType = PartnerTypes.Gold;
     userRepository.Save(user); // the user in member name is useless
     eventsRepository.Save(new Event(){Message = "The user" + UserId + "is golden" });
  }
} 

good luck :)