'Service layer user vs admin best practice

Have an application that is quiet large and am rethinking some of the design and wondering if the practices currently in use are correct. I will keep it simple as there its not about coding.

Assume we have a method in a service that we call like _userService.GetUser(..). This method returns a user as expected. If the method is called for a logged in user the method has checks to ensure the user can only see their details.

Now if the method is called by administrator they can retrieve any user and checks are bypassed. Again code not important here.

Questions

  1. Better to separate out the methods per user and per admin
  2. Better to have UserService and AdminUserService?
  3. Should the check be done at DB level and not return a record if it does not match criteria or after loading the entire object and checking properties (current practice)

I am wondering if there are best practices for this because looking at various large projects it seems that most systems write single methods and just deal with logic to determine what to do for the incoming request.



Solution 1:[1]

You can create two different service, user service and admin service. compose user service with user related classes and compose admin service with user and admin related classes. thus you achieve separation of concern and independent flow in both execution path.

Now you can call out any service depending upon what type of user it is. So no repetition of code, just need to introduce one layer to manage your operation flow.

Solution 2:[2]

Generally, in a read operation you shouldn't get more data than you need from your DB, simply because it's not resource optimal.

Also, if you consider the query patterns, I believe users are more likely to query their profile (more frequently), than it is for an admin.

For that reason, I would create separate flows (end-to-end) for those 2 access patterns, including separate services (AdminUserService), and separate data access layers. This way you make all layers of testing cleaner.

Now this is only one way of seeing the problem. Of course you can adapt this depending on your performance considerations and on the evolvability directions of your project.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sanjay Soni
Solution 2 Cosmin Ioni??