Data access level - development class, where responsibility for creating persistence

I am developing a Data Access Layer with ADO.NET 2.0 and C #, Sql Server 2005. I often struggle with my brain about where to place these calls. Which of the methods below should I follow for supported reliable code.

Method 1

Public Class Company { public string CompanyId {get;set;} public string CompanyAddress {get;set;} public bool Create() { } public bool Update() { } public bool Delete() { } } 

Method 2

 Public Class Company { public string CompanyId {get;set;} public string CompanyAddress {get;set;} } 

and I would use another class, as shown below, to access the main data. As below

 Public Class CompanyRepository { public Company CreateCompany(string companyId,string companyDescription) { } public bool UpdateCompany(Company updateCompany) { } public bool DeleteCompany(string companyId) { } public List<Company> FindById(string id) { } } 
+6
source share
3 answers

Follow the method 2. Responsibility for reading / writing from the data source ( the company does not bear the principle of responsibility) . However, I would even get to creating the ICompanyRepository interface, and then create a CompanyRepository implementation for the interface. Thus, you can enter ICompanyRepository in a class that should save / retrieve company information. It also allows simplifying unit testing and the possibility of creating another implementation in the future (switching from a database to xml files or something else).

+7
source

If you follow the principle of separation of concerns , you will go with your method 2.

Having different responsibilities in different classes helps create test, supported code.

It also creates smaller, more cohesive classes that are easier to write, reason, and validate.

As a note, you can use ORM instead of manually creating your level of data access.

+2
source

I would choose the second option, calling

  • first create data holder
  • after the operational unit basket

Thus, in this case, you separate the data from the functions that work on them, making UnitTesting noticeably simpler and distributing responsibilities between the different domains of your code, with, possibly, the ease of error localization.

+1
source

Source: https://habr.com/ru/post/906025/


All Articles