Repositories have very simple and single aim - i.e. to do CRUD (Create, Read, Update, Delete) operations on data. Following points need to consider when you create a Repository class.
Stay limited
- It must have methods like Create, Update, Delete. These methods can have their overloads
- To return a list of objects create a method called “LIst()”. Create overloads as per need
- If you wish to return a single record then it’s good to create a method like Read() or Get(). Use primary key value as parameter to locate your record
Follow technical responsibility
Do not write any logic in repository, keep it limited to CRUD operations so that it does not violate
Single Responsibility Principle (a technical responsibility).
Follow functional responsibility
- Consider that you are dealing with two entities - Employee, Department.
- When you write EmployeeRepository then deal with employees & employees only. Do not update, return, delete Department records even if it has a relationship with employee.
- Also, when you write DepartmentRepository then deal with department entries only if you return employee entries it will violate Single Responsibility Principle (a functional responsibility)
- Now you have an obvious question that how can your return employees in specific department. So, to do it simply create a method “List(departmentID)” (in case if you are out of overloads then still you have the opportunity to write a method ListByDepartmentID).
Performance is mandatory
- Following performance consideration are must while writing Repositories
- If you have less than 100 or fixed entries to return then its fine to return a full list but if count exceeds 100 then it’s always better to use Paged Lists so that you make efficient use of data
Large datasets consume high memory, high network traffic, ultimately slow response to client
- Stay precocious while writing batch updates or deletes. There is no specific guidelines to not to have loops inside Update or Delete methods but adding loops is like adding some logic so ideally it violates technical responsibility and slows down Repository response (Still moving it out of repository does not yield any gain in terms of overall performance but a Repository performance)
Conclusion
Repositories should perform CRUD operations in an efficient way without violating technical and functional responsibilities.
No comments:
Post a Comment