IT박스

엔티티 객체가 필요한 이유는 무엇입니까?

itboxs 2020. 6. 21. 20:28
반응형

엔티티 객체가 필요한 이유는 무엇입니까? [닫은]


현재 수용되는 엔터프라이즈 응용 프로그램 디자인 패러다임 의 장점에 대한 정직하고 사려 깊은 토론이 필요합니다 .

엔티티 객체가 존재해야한다고 확신하지 않습니다.

엔터티 객체라는 말은 "개인", "계정", "주문"등과 같이 응용 프로그램을 위해 구축하려는 전형적인 것들을 의미합니다.

나의 현재 디자인 철학은 다음과 같습니다.

  • 모든 데이터베이스 액세스는 저장 프로 시저를 통해 수행해야합니다.
  • 데이터가 필요할 때마다 저장 프로 시저를 호출하고 SqlDataReader 또는 DataTable의 행을 반복합니다.

(참고 : Java EE를 사용하여 엔터프라이즈 응용 프로그램을 구축했으며 Java 사람들은 내 .NET 예제와 동등한 것을 대체하십시오)

나는 안티 -OO가 아닙니다. 엔티티가 아닌 다른 목적으로 많은 클래스를 작성합니다. 필자가 작성한 클래스의 대부분이 정적 도우미 클래스라는 것을 인정할 것입니다.

나는 장난감을 만들고 있지 않다. 여러 컴퓨터에 배포 된 대용량 트랜잭션 응용 프로그램에 대해 이야기하고 있습니다. 웹 응용 프로그램, Windows 서비스, 웹 서비스, b2b 상호 작용 등이 있습니다.

OR 매퍼를 사용했습니다. 나는 몇 가지를 썼다. Java EE 스택, CSLA 및 기타 몇 가지를 사용했습니다. 나는 그것들을 사용할뿐만 아니라 프로덕션 환경에서 이러한 응용 프로그램을 적극적으로 개발하고 유지 관리했습니다.

나는 엔티티 객체가 우리의 방법으로 받고 있는지 전투 테스트 결론에 도달 한 우리의 생활은 것 때문에 훨씬 더 쉽게 그들없이.

이 간단한 예를 고려하십시오. 응용 프로그램에서 올바르게 작동하지 않는 특정 페이지에 대한 지원 요청이있을 수 있습니다. 필드 중 하나가 그대로 유지되지 않을 수 있습니다. 내 모델에서 문제를 찾도록 지정된 개발자는 정확히 3 개의 파일을 엽니 다 . 저장 프로 시저가있는 ASPX, ASPX.CS 및 SQL 파일 저장 프로 시저 호출에 누락 된 매개 변수 일 수있는 문제는 해결하는 데 몇 분이 걸립니다. 그러나 모든 엔터티 모델을 사용하면 디버거가 항상 실행되고 코드 단계별 실행이 시작되며 Visual Studio에서 15-20 개의 파일이 열릴 수 있습니다. 스택 맨 아래로 내려갈 때 시작한 위치를 잊었습니다. 한 번에 너무 많은 것들을 머릿속에 유지할 수 있습니다. 불필요한 레이어를 추가하지 않고도 소프트웨어가 매우 복잡합니다.

개발의 복잡성과 문제 해결은 저의 한 측면 일뿐입니다.

이제 확장성에 대해 이야기하겠습니다.

개발자는 데이터베이스와 상호 작용하는 코드를 작성하거나 수정할 때마다 데이터베이스에 미치는 정확한 영향을 철저히 분석해야한다는 것을 알고 있습니까? 그리고 개발 사본뿐만 아니라 생산 모방을 의미하므로 개체에 필요한 추가 열이 현재 쿼리 계획을 무효화하고 1 초 안에 실행되는 보고서가 이제 2 분이 걸립니다. 선택 목록에 단일 열을 추가했기 때문에? 그리고 지금 필요한 색인이 너무 커서 DBA가 파일의 실제 레이아웃을 수정해야합니까?

사람들이 추상화를 통해 물리적 데이터 저장소에서 너무 멀리 떨어져 있으면 확장이 필요한 응용 프로그램으로 인해 혼란을 초래할 수 있습니다.

나는 열광자가 아닙니다. Linq에 대한 Sql, ADO.NET EF, Hibernate, Java EE 등으로의 강력한 추진력이 있기 때문에 내가 틀렸다면 확신 할 수 있습니다. 그것이 무엇인지, 왜 생각을 바꿔야하는지 알고 싶습니다.

[편집하다]

이 질문이 갑자기 다시 활성화 된 것 같습니다. 이제 몇 가지 답변에 직접 댓글을 추가 한 새로운 댓글 기능이 생겼습니다. 답장을 보내 주셔서 감사합니다. 이것이 건강한 토론이라고 생각합니다.

엔터프라이즈 응용 프로그램에 대해 이야기하고 있다는 것이 더 분명했을 것입니다. 예를 들어 누군가의 데스크톱 또는 모바일 앱에서 실행되는 게임에 대해서는 언급 할 수 없습니다.

몇 가지 유사한 답변에 대한 응답으로 내가 여기에 올려야 할 한 가지는 직교성과 우려의 분리가 종종 실체 / ORM의 근거로 인용되는 것입니다. 저에게있어 저장 절차는 제가 생각할 수있는 우려를 분리하는 가장 좋은 예입니다. 저장 프로 시저를 통하지 않고 데이터베이스에 대한 다른 모든 액세스를 허용하지 않으면 저장 프로 시저의 입력 및 출력을 유지하는 한 이론적으로 전체 데이터 모델을 다시 디자인하고 코드를 중단하지 않을 수 있습니다. 계약에 의한 프로그래밍의 완벽한 예입니다 ( "select *"를 피하고 결과 세트를 문서화하는 한).

오랫동안 업계에 종사해 왔으며 오래 지속되는 응용 프로그램을 사용해 본 사람에게 물어보십시오. 데이터베이스가 살아있는 동안 몇 개의 응용 프로그램 및 UI 계층이왔다 갔다합니까? 데이터를 얻기 위해 SQL을 생성하는 4 개 또는 5 개의 서로 다른 지속성 계층이있을 때 데이터베이스를 조정하고 리팩토링하는 것이 얼마나 어렵습니까? 아무것도 바꿀 수 없습니다! ORM 또는 SQL을 생성하는 코드는 데이터베이스를 석쇠로 잠급니다 .


응용 프로그램의 "논리적"이 얼마나 복잡한 지, 그리고 응용 프로그램을 구현 한 위치에 달려 있다고 생각합니다. 모든 논리가 저장 프로 시저에 있고 모든 응용 프로그램에서 해당 프로 시저를 호출하고 결과를 표시하는 경우 엔터티 개체 개발은 실제로 시간 낭비입니다. 그러나 객체가 서로 상호 작용하고 데이터베이스가 지속성 메커니즘 인 응용 프로그램의 경우 해당 객체를 갖는 것이 가치가있을 수 있습니다.

그래서, 나는 하나의 크기에 맞는 대답이 없다고 말하고 싶습니다. 개발자는 때때로 너무 OO가 되려고 시도하면 해결하는 것보다 더 많은 문제가 발생할 수 있음을 알고 있어야합니다.


이론에 따르면 응집력이 높고 느슨하게 결합 된 구현이 앞으로 나아갈 수 있다고합니다.

그래서 나는 당신이 그 접근법, 즉 우려를 분리시키는 것에 대해 질문하고 있다고 가정합니다.

내 aspx.cs 파일이 데이터베이스와 상호 작용하고 sproc을 호출하며 IDataReader를 이해해야합니까?

팀 환경, 특히 응용 프로그램의 aspx 부분을 다루는 기술 담당자가 적은 경우에는 이러한 사람들이이 자료를 "만질"필요가 없습니다.

내 도메인을 내 데이터베이스에서 분리하면 데이터베이스의 구조적 변경으로부터 나를 보호 할 수 있습니다. 데이터베이스의 효율성은 절대적으로 중요합니다. 따라서 해당 작업을 가장 잘 수행하는 사람이 한 시스템에서 나머지 시스템에 거의 영향을 미치지 않으면 서 해당 작업을 처리하도록하십시오.

내가 당신의 접근 방식을 오해하지 않는 한, 데이터베이스에서 하나의 구조적 변화는 응용 프로그램의 표면에 큰 영향을 줄 수 있습니다. 이러한 우려가 분리되어 저와 제 팀은이를 최소화 할 수 있습니다. 또한 팀의 새로운 구성원은이 접근 방식을 더 잘 이해해야합니다.

또한 귀하의 접근 방식은 응용 프로그램의 비즈니스 논리를 데이터베이스에 상주시키는 것으로 보입니까? 이것은 나에게 잘못 느낀다. SQL은 비즈니스 로직을 표현하는 것이 아니라 데이터를 쿼리하는 데 능숙하다.

그럼에도 불구하고 흥미로운 생각은 aspx의 SQL에서 한 발짝 떨어져 있다고 생각하지만, 오래된 오래된 비정형 ASP 시대에서 나는 두려움으로 가득 차 있습니다.


한 가지 이유-데이터베이스 모델에서 도메인 모델을 분리합니다.

내가하는 일은 Test Driven Development를 사용하여 UI와 Model 레이어를 먼저 작성하고 Data 레이어를 조롱하여 UI와 모델이 도메인 특정 객체를 기반으로 빌드 한 다음 나중에이 객체를 내가 사용중인 기술에 매핑하는 것입니다. 데이터 레이어. 데이터베이스 구조가 응용 프로그램의 디자인을 결정하게하는 것은 나쁜 생각입니다. 가능한 경우 먼저 앱을 작성하고 다른 방식이 아닌 데이터베이스 구조에 영향을 미치도록하십시오.


나를 위해 그것은 응용 프로그램이 데이터 저장 방법에 관심을 가지기를 원하지 않습니다. 아마이 말을 할 수있을 것입니다 ...하지만 응용 프로그램은 데이터가 아니며 데이터는 응용 프로그램의 인공물입니다. 내 응용 프로그램이 DataSets, DataTables 및 DataRows와 같은 기술이 아닌 고객, 주문 및 항목의 관점에서 생각하기를 원합니다.

나는 항상 일정한 양의 커플 링이 있다는 것에 동의하지만, 커플 링은 아래쪽보다는 오히려 위쪽에 도달하는 것을 선호합니다. 나무의 가지와 잎을 몸통을 바꾸는 것보다 쉽게 ​​조정할 수 있습니다.

쿼리가 응용 프로그램의 일반 데이터 액세스보다 약간 나 빠지기 때문에보고를 위해 sproc을 예약하는 경향이 있습니다.

또한 하나의 열이 유지되지 않는 것처럼 시나리오의 초기에 적절한 단위 테스트를 수행하는 것이 문제가되지 않을 것이라고 생각하는 경향이 있습니다.


에릭, 넌 죽었어 실제로 확장 가능하고 쉽게 유지 관리 할 수 ​​있고 강력한 응용 프로그램의 경우 유일한 해결책은 모든 쓰레기를 없애고 기본 사항을 고수하는 것입니다.

나는 내 경력과 비슷한 궤적을 따랐으며 같은 결론에 도달했다. 물론, 우리는 이단자로 여겨지고 재미있었습니다. 그러나 내 물건은 잘 작동합니다.

모든 코드 줄은 의심으로 봐야합니다.


제안한 것과 비슷한 예를 들어 대답하고 싶습니다.

회사에서 제품에 대한 간단한 CRUD 섹션을 작성해야했고 모든 엔티티와 별도의 DAL을 작성했습니다. 나중에 다른 개발자가 관련 테이블을 변경해야했으며 여러 필드의 이름을 변경하기까지했습니다. 양식을 업데이트하기 위해 변경해야하는 유일한 파일은 해당 테이블의 DAL이었습니다.

엔티티가 프로젝트에 가져 오는 것은 다음과 같습니다.

직교성 : 한 계층의 변경 사항은 다른 계층에 영향을 미치지 않을 수 있습니다 (물론 데이터베이스를 크게 변경하면 모든 계층에 영향을 주지만 대부분의 작은 변경 사항은 적용되지 않습니다).

테스트 가능성 : 데이터베이스를 건드리지 않고도 로직을 테스트 할 수 있습니다. 이렇게하면 테스트 성능이 향상됩니다 (더 자주 실행할 수 있음).

우려의 분리 : 큰 제품에서는 데이터베이스를 DBA에 할당 할 수 있으며이를 통해 지옥을 최적화 할 수 있습니다. 설계에 필요한 지식이있는 비즈니스 전문가에게 모델을 지정하십시오. 웹 양식 등에서 더 경험이 많은 개발자에게 개별 양식을 할당하십시오.

마지막으로 대부분의 ORM 맵퍼가 저장 프로 시저를 지원한다고 덧붙이고 싶습니다.

건배.


나는 당신이이 주제에 대해 "당신이 씹을 수있는 것보다 더 많이 물지 않을 것"이라고 생각합니다. Ted Neward는 " 컴퓨터 과학의 베트남 "이라고 불렀을 때 플립 팬트가 아니 었습니다 .

내가 당신을 절대적으로 보장 할 수있는 한 가지는 무수히 많은 다른 블로그, 포럼, 팟 캐스트 등에서 종종 입증 된 것처럼 문제에 대한 아무도의 견해를 바꿀 수 없다는 것입니다.

논란의 여지가있는 주제에 대해 공개적인 토론과 토론을하는 것은 확실히 괜찮습니다. 두 가지 측면이 모두 동의하지 않고 소프트웨어 작성에 착수 한 것은 너무나 많은 일입니다.

양쪽에 대해 더 자세히 읽으려면 Ted의 블로그, Ayende Rahein, Jimmy Nilson, Scott Bellware, Alt.Net, Stephen Forte, Eric Evans 등의 기사를 참조하십시오.


@Dan, 죄송합니다. 제가 찾는 것은 아닙니다. 나는 이론을 안다. 당신의 진술은 "아주 나쁜 생각이다"는 실제 사례에 의해 뒷받침되지 않습니다. 우리는 적은 시간, 적은 인원, 적은 실수로 소프트웨어를 개발하려고 노력하고 있으며 쉽게 변경할 수있는 기능을 원합니다. 내 경험상, 귀하의 다층 모델은 위의 모든 범주에서 부정적입니다. 특히 데이터 모델을 마지막으로 만드는 것과 관련하여. 물리적 데이터 모델은 1 일부터 중요한 고려 사항이어야합니다.


귀하의 질문이 정말 흥미 롭습니다.
일반적으로 응용 프로그램의 비즈니스 논리를 캡슐화하려면 엔터티 개체가 필요합니다. 이 논리를 데이터 계층에 적용하는 것은 실제로 복잡하고 부적절합니다.
이러한 개체 개체를 피하기 위해 무엇을 하시겠습니까? 어떤 솔루션을 염두에두고 있습니까?


엔터티 개체는 응용 프로그램 계층에서 캐시를 용이하게 할 수 있습니다. 데이터 리더를 캐싱하는 것이 좋습니다.


또한 실체가 무엇인지에 대한 개념에 대해서도 이야기해야합니다. 이 토론을 읽으면 대부분의 사람들이 빈혈 도메인 모델 의 의미에서 엔티티를보고 있다는 인상을받습니다 . 많은 사람들이 Anemic Domain Model을 반 패턴으로 고려하고 있습니다!

리치 도메인 모델에는 가치가 있습니다. 이것이 바로 도메인 기반 디자인의 핵심 입니다. 저는 개인적으로 OO가 복잡성을 극복하는 방법이라고 믿습니다. 이는 데이터 액세스, UI 바인딩, 보안과 같은 기술적 복잡성 뿐만 아니라 비즈니스 영역의 복잡성도 의미합니다 !

비즈니스 문제 를 분석, 모델링, 설계 및 구현 하기 위해 OO 기술을 적용 할 수 있다면 , 이는 사소한 응용 프로그램의 유지 관리 성과 확장성에있어 엄청난 이점입니다!

엔터티와 테이블간에 차이가 있습니다. 엔티티는 모델을 나타내야하며 테이블은 모델의 데이터 측면을 나타냅니다!

데이터는 앱보다 수명이 길지만 David Laribee의 인용문고려 하십시오 . 모델은 영원히 ... 데이터는 행복한 부작용입니다.

이 주제에 대한 더 많은 링크 :


정말 흥미로운 질문입니다. 솔직히 나는 엔티티가 좋은 이유를 증명할 수 없습니다. 그러나 내가 왜 그들을 좋아하는지 의견을 공유 할 수 있습니다. 같은 코드

void exportOrder(Order order, String fileName){...};

DataRow를 가져 와서 예상되는 열과 필요한 유형을 문서화하는 대신 DB에서, 웹 요청, 단위 테스트 등에서 주문이 어디에서 왔는지 걱정하지 않습니다. 있다. 저장 프로 시저로 구현 한 경우에도 동일하게 적용됩니다. 레코드 ID를 여전히 푸시해야하지만 DB에는 없어야합니다.

이 방법의 구현은 DB에 정확히 표시되는 방법이 아니라 주문 추상화를 기반으로 수행됩니다. 내가 구현 한 이러한 작업의 대부분은 실제로이 데이터가 저장되는 방법에 의존하지 않습니다. 일부 작업에는 성능과 확장 성을 위해 DB 구조와의 연결이 필요하다는 것을 이해합니다. 내 경험으로는 너무 많지 않습니다. 내 경험상 Person이 String을 반환하는 .getFirstName ()과 Address를 반환하는 .getAddress ()를 가지고 있고 address가 .getZipCode () 등을 가지고 있다는 것을 알고 충분합니다. .

추가 열이 보고서 성능을보고 할 때와 같이 설명 된대로 이러한 문제를 처리해야하는 경우 작업의 경우 DB가 중요한 부분이므로 실제로 가능한 한 가까이 있어야합니다. 엔티티는 편리한 추상화를 제공 할 수 있지만 중요한 세부 사항도 숨길 수 있습니다.

확장 성은 흥미로운 점입니다. 페이스 북, 라이브 저널, 플리커와 같이 엄청난 확장 성을 필요로하는 대부분의 웹 사이트는 DB를 최대한 드물게 사용하고 캐싱, 특히 RAM 사용으로 확장 성 문제를 해결할 때 DB-ascetic 방식을 사용하는 경향이 있습니다. http://highscalability.com/ 에 흥미로운 기사가 ​​있습니다.


추상화 및 느슨한 결합 외에도 엔티티 객체에 대한 다른 좋은 이유가 있습니다. 내가 가장 좋아하는 것 중 하나는 DataReader 또는 DataTable로는 얻을 수없는 강력한 타이핑입니다. 또 다른 이유는 잘 수행되면 적절한 엔티티 클래스가 코드를 보는 사람이 필드 이름이있는 문자열이 아닌 이해할 수있는 도메인 특정 용어에 대해 일류 구문을 사용하여 코드를 유지 관리 할 수 ​​있기 때문입니다. DataRow를 인덱싱합니다. 많은 매핑 프레임 워크가 sproc에 매핑 할 수 있기 때문에 저장 프로시 저는 실제로 ORM 사용과 직교합니다.

나는 sprocs + datareaders가 좋은 ORM을 대신한다고 생각하지 않습니다. 저장 프로 시저를 사용하면 호출 코드와 다른 형식 시스템을 사용하는 프로 시저의 형식 서명에 여전히 구속되어 있고 밀접하게 연결되어 있습니다. 저장 프로시 저는 추가 옵션 및 스키마 변경을 수용하기 위해 수정 될 수 있습니다. 스키마가 변경 될 경우 저장 프로 시저의 대안은 뷰를 사용하는 것입니다. 개체를 뷰에 매핑 한 다음 변경시 기본 테이블에 뷰를 다시 매핑 할 수 있습니다.

I can understand your aversion to ORMs if your experience mainly consists of Java EE and CSLA. You might want to have a look at LINQ to SQL, which is a very lightweight framework and is primarily a one-to-one mapping with the database tables but usually only needs minor extension for them to be full-blown business objects. LINQ to SQL can also map input and output objects to stored procedures' paramaters and results.

The ADO.NET Entity framework has the added advantage that your database tables can be viewed as entity classes inheriting from each other, or as columns from multiple tables aggregated into a single entity. If you need to change the schema, you can change the mapping from the conceptual model to the storage schema without changing the actual application code. And again, stored procedures can be used here.

I think that more IT projects in enterprises fail because of unmaintainability of the code or poor developer productivity (which can happen from, e.g., context switching between sproc-writing and app-writing) than scalability problems of an application.


I would also like to add to Dan's answer that separating both models could enable your application to be run on different database servers or even database models.


What if you need to scale your app by load balancing more than one web server? You could install the full app on all web servers, but a better solution is to have the web servers talk to an application server.

But if there aren't any entity objects, they won't have very much to talk about.

단순하고 내부적이며 수명이 짧은 응용 프로그램이라면 모놀리스를 작성해서는 안된다는 말은 아닙니다. 그러나 적당히 복잡해 지거나 상당한 시간이 걸리면 좋은 디자인을 생각해야합니다.

이를 통해 유지 관리에 소요되는 시간을 절약 할 수 있습니다.

응용 프로그램 논리를 프레젠테이션 논리와 데이터 액세스에서 분리하고 DTO를 전달함으로써 분리합니다. 독립적으로 변경할 수 있습니다.


comp.object 에서이 게시물을 찾을 수 있습니다 .

나는 동의하거나 동의하지 않는다고 주장하지는 않지만 흥미롭고이 주제와 관련이 있다고 생각합니다.


질문 : 모든 비즈니스 로직이 데이터베이스에 갇힌 경우 연결이 끊어진 응용 프로그램을 어떻게 처리합니까?

In the type of Enterprise application I'm interested in, we have to deal with multiple sites, some of them must be able to function in a disconnected state.
If your business logic is encapsulated in a Domain layer that is simple to incorporate into various application types -say, as a dll- then I can build applications that are aware of the business rules and are able, when necessary, to apply them locally.

In keeping the Domain layer in stored procedures on the database you have to stick with a single type of application that needs a permanent line-of-sight to the database.

It's ok for a certain class of environments, but it certainly doesn't cover the whole spectrum of Enterprise applications.


@jdecuyper, one maxim I repeat to myself often is "if your business logic is not in your database, it is only a recommendation". I think Paul Nielson said that in one of his books. Application layers and UI come and go, but data usually lives for a very long time.

How do I avoid entity objects? Stored procedures mostly. I also freely admit that business logic tends to reach through all layers in an application whether you intend it to or not. A certain amount of coupling is inherent and unavoidable.


I have been thinking about this same thing a lot lately; I was a heavy user of CSLA for a while, and I love the purity of saying that "all of your business logic (or at least as much as is reasonably possible) is encapsulated in business entities".

I have seen the business entity model provide a lot of value in cases where the design of the database is different than the way you work with the data, which is the case in a lot of business software.

For example, the idea of a "customer" may consist of a main record in a Customer table, combined with all of the orders the customer has placed, as well as all the customer's employees and their contact information, and some of the properties of a customer and its children may be determined from lookup tables. It's really nice from a development standpoint to be able to work with the Customer as a single entity, since from a business perspective, the concept of Customer contains all of these things, and the relationships may or may not be enforced in the database.

While I appreciate the quote that "if your business rule is not in your database, it's only a suggestion", I also believe that you shouldn't design the database to enforce business rules, you should design it to be efficient, fast and normalized.

That said, as others have noted above, there is no "perfect design", the tool has to fit the job. But using business entities can really help with maintenance and productivity, since you know where to go to modify business logic, and objects can model real-world concepts in an intuitive way.


Eric,

No one is stopping you from choosing the framework/approach that you would wish. If you are going to go the "data driven/stored procedure-powered" path, then by all means, go for it! Especially if it really, really helps you deliver your applications on-spec and on-time.

The caveat being (a flipside to your question that is), ALL of your business rules should be on stored procedures, and your application is nothing more than a thin client.

That being said, same rules apply if you do your application in OOP : be consistent. Follow OOP's tenets, and that includes creating entity objects to represent your domain models.

The only real rule here is the word consistency. Nobody is stopping you from going DB-centric. No one is stopping you from doing old-school structured (aka, functional/procedural) programs. Hell, no one is stopping anybody from doing COBOL-style code. BUT an application has to be very, very consistent once going down this path, if it wishes to attain any degree of success.


I'm really not sure what you consider "Enterprise Applications". But I'm getting the impression you are defining it as an Internal Application where the RDBMS would be set in stone and the system wouldn't have to be interoperable with any other systems whether internal or external.

But what if you had a database with 100 tables which equate to 4 Stored Procedures for each table just for basic CRUD operations that's 400 stored procedures which need to be maintained and aren't strongly-typed so are susceptible to typos nor can be Unit Tested. What happens when you get a new CTO who is an Open Source Evangelist and wants to change the RDBMS from SQL Server to MySql?

A lot of software today whether Enterprise Applications or Products are using SOA and have some requirements for exposing Web Services, at least the software I am and have been involved with do. Using your approach you would end up exposing a Serialized DataTable or DataRows. Now this may be deemed acceptable if the Client is guaranteed to be .NET and on an internal network. But when the Client is not known then you should be striving to Design an API which is intuitive and in most cases you would not want to be exposing the Full Database schema. I certainly wouldn't want to explain to a Java developer what a DataTable is and how to use it. There's also the consideration of Bandwith and payload size and serialized DataTables, DataSets are very heavy.

There is no silver bullet with software design and it really depends on where the priorities lie, for me it's in Unit Testable code and loosely coupled components that can be easily consumed be any client.

just my 2 cents


I'd like to offer another angle to the problem of distance between OO and RDB: history.

Any software has a model of reality that is to some degree an abstraction of reality. No computer program can capture all the complexities of reality, and programs are written just to solve a set of problems from reality. Therefore any software model is a reduction of reality. Sometimes the software model forces reality to reduce itself. Like when you want the car rental company to reserve any car for you as long as it is blue and has alloys, but the operator can't comply because your request won't fit in the computer.

RDB comes from a very old tradition of putting information into tables, called accounting. Accounting was done on paper, then on punch cards, then in computers. But accounting is already a reduction of reality. Accounting has forced people to follow its system so long that it has become accepted reality. That's why it is relatively easy to make computer software for accounting, accounting has had its information model, long before the computer came along.

Given the importance of good accounting systems, and the acceptance you get from any business managers, these systems have become very advanced. The database foundations are now very solid and noone hesitates about keeping vital data in something so trustworthy.

I guess that OO must have come along when people have found that other aspects of reality are harder to model than accounting (which is already a model). OO has become a very successful idea, but persistance of OO data is relatively underdeveloped. RDB/Accounting has had easy wins, but OO is a much larger field (basically everything that isn't accounting).

So many of us have wanted to use OO but we still want safe storage of our data. What can be safer than to store our data the same way as the esteemed accounting system does? It is an enticing prospects, but we all run into the same pitfalls. Very few have taken the trouble to think of OO persistence compared to the massive efforts by the RDB industry, who has had the benefit of accounting's tradition and position.

Prevayler and db4o are some suggestions, I'm sure there are others I haven't heard of, but none have seemed to get half the press as, say, hibernation.

Storing your objects in good old files doesn't even seem to be taken seriously for multiuser applications, and especially web applications.

In my everyday struggle to close the chasm between OO and RDB I use OO as much as possible but try to keep inheritance to a minimum. I don't often use SPs. I'll use the advanced query stuff only in aspects that look like accounting.

I'll be happily supprised when the chasm is closed for good. I think the solution will come when Oracle launches something like "Oracle Object Instance Base". To really catch on, it will have to have a reassuring name.


Not a lot of time at the moment, but just off the top of my head...

The entity model lets you give a consistent interface to the database (and other possible systems) even beyond what a stored procedure interface can do. By using enterprise-wide business models you can make sure that all applications affect the data consistently which is a VERY important thing. Otherwise you end up with bad data, which is just plain evil.

If you only have one application then you don't really have an "enterprise" system, regardless of how big that application or your data are. In that case you can use an approach similar to what you talk about. Just be aware of the work that will be needed if you decide to grow your systems in the future.

Here are a few things that you should keep in mind (IMO) though:

  1. Generated SQL code is bad (exceptions to follow). Sorry, I know that a lot of people think that it's a huge time saver, but I've never found a system that could generate more efficient code than what I could write and often the code is just plain horrible. You also often end up generating a ton of SQL code that never gets used. The exception here is very simple patterns, like maybe lookup tables. A lot of people get carried away on it though.
  2. Entities <> Tables (or even logical data model entities necessarily). A data model often has data rules that should be enforced as closely to the database as possible which can include rules around how table rows relate to each other or other similar rules that are too complex for declarative RI. These should be handled in stored procedures. If all of your stored procedures are simple CRUD procs, you can't do that. On top of that, the CRUD model usually creates performance issues because it doesn't minimize round trips across the network to the database. That's often the biggest bottleneck in an enterprise application.

Sometimes, your application and data layer are not that tightly coupled. For example, you may have a telephone billing application. You later create a separate application which monitors phone usage to a) better advertise to you b) optimise your phone plan.

These applications have different concerns and data requirements (even the data is coming out of the same database), they would drive different designs. Your code base can end up an absolute mess (in either application) and a nightmare to maintain if you let the database drive the code.


Applications that have domain logic separated from the data storage logic are adaptable to any kind of data source (database or otherwise) or UI (web or windows(or linux etc.)) application.

Your pretty much stuck in your database, which isn't bad if your with a company who is satisfied with the current database system your using. However, because databases evolve overtime there might be a new database system that is really neat and new that your company wants to use. What if they wanted to switch to a web services method of data access (like Service Orientated architecture sometime does). You might have to port your stored procedures all over the place.

Also the domain logic abstracts away the UI, which can be more important in large complex systems that have ever evolving UIs (especially when they are constantly searching for more customers).

Also, while I agree that there is no definitive answer to the question of stored procedures versus domain logic. I'm in the domain logic camp (and I think they are winning over time), because I believe that elaborate stored procedures are harder to maintain than elaborate domain logic. But that's a whole other debate


I think that you are just used to writing a specific kind of application, and solving a certain kind of problem. You seem to be attacking this from a "database first" perspective. There are lots of developers out there where data is persisted to a DB but performance is not a top priority. In lots of cases putting an abstraction over the persistence layer simplifies code greatly and the performance cost is a non-issue.

Whatever you are doing, it's not OOP. It's not wrong, it's just not OOP, and it doesn't make sense to apply your solutions to every othe problem out there.


Interesting question. A couple thoughts:

  1. How would you unit test if all of your business logic was in your database?
  2. Wouldn't changes to your database structure, specifically ones that affect several pages in your app, be a major hassle to change throughout the app?

Good Question!

One approach I rather like is to create an iterator/generator object that emits instances of objects that are relevant to a specific context. Usually this object wraps some underlying database access stuff, but I don't need to know that when using it.

For example,

An AnswerIterator object generates AnswerIterator.Answer objects. Under the hood it's iterating over a SQL Statement to fetch all the answers, and another SQL statement to fetch all related comments. But when using the iterator I just use the Answer object that has the minimum properties for this context. With a little bit of skeleton code this becomes almost trivial to do.

I've found that this works well when I have a huge dataset to work on, and when done right, it gives me small, transient objects that are relatively easy to test.

It's basically a thin veneer over the Database Access stuff, but it still gives me the flexibility of abstracting it when I need to.


The objects in my apps tend to relate one-to-one to the database, but I'm finding using Linq To Sql rather than sprocs makes it much easier writing complicated queries, especially being able to build them up using the deferred execution. e.g. from r in Images.User.Ratings where etc. This saves me trying to work out several join statements in sql, and having Skip & Take for paging also simplifies the code rather than having to embed the row_number & 'over' code.


Why stop at entity objects? If you don't see the value with entity objects in an enterprise level app, then just do your data access in a purely functional/procedural language and wire it up to a UI. Why not just cut out all the OO "fluff"?

참고URL : https://stackoverflow.com/questions/18655/why-do-we-need-entity-objects

반응형