Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# classes and methods

Tags:

c#

oop

I find it difficult to determine the responsiblity of classes: do i have to put this method in this class or should I put this method in another class? For example, imagine a simple User class with an id, forname, lastname and password. Now you have an userId and you want the forname and lastname, so you create a method like: public User GetUserById(int id){}. Next you want to show list of all the users, so you create another method: public List GetAllUsers(){}. And offcourse you want to update, delete and save a user. This gives us 5 methods:

public bool SaveUser(User user);
public bool UpdateUser(User user);
public bool DeleteUser(User user);
public User GetUserById(int id);
public List<User> GetAllUsers();

So my question is: do you put all these methods in the User class? Or do you create another data class (UserData class) which may connect to the database and contain all these methods?

like image 477
Martijn Avatar asked Dec 05 '22 06:12

Martijn


2 Answers

What you are describing here is basically a choice between the Active Record Pattern or the Repository Pattern. I'd advise you to read up on those patterns and choose whichever one fits your application / experience / toolset.

like image 82
Steve Willcock Avatar answered Dec 09 '22 16:12

Steve Willcock


I would not put those specific methods into the 'User' class.

There are 2 common approaches for this 'problem':

  • You put those method in the User class, and then this means you 're using the Active Record pattern
  • You put those methods in a separate class (UserRepository) for instance, and then you're using the Repository pattern.

I prefer the repository-approach, since that keeps my 'User' class clean, and doesn't clutter it with data access code.

like image 41
Frederik Gheysels Avatar answered Dec 09 '22 16:12

Frederik Gheysels