scorpio
scorpio

Reputation: 11

Why not have Domains directly extend GenericDAO?

My question may be a bit basic, but wanted to run this through Stack Overflow folks.

Usual practice is to have Domain classes (with properties and getters/setters, say User.java). Then have DAOs (says UserDAO.java which extends GenericDAO.java) to provide CRUD operations.

What if we make domains extend the GenericDAO? Like User.java extends GenericDAO, which allows us to have something like this:

user.save();

I've worked on Grails and if you know Grails you'd understand why this question. Also have a bit of idea about Domain Driven Design, which I guess suggests something similar. I found an article on DDD which says:

The clients should always call the domain objects which in turn should call the DAO's for persisting the data to the data store.

Just wanted to know if there are any disadvantages why people not use it this way?

Upvotes: 0

Views: 96

Answers (2)

guillaume31
guillaume31

Reputation: 14080

It's mainly about the Single Responsibility Principle and separation of concerns -- in DDD, Domain layer objects are specialized in modelling the domain and enforcing its invariants. Whether, how or when data is persisted is none of their business, these are different concerns handled by other code modules.

Some benefits of SRP and smaller class scope are : readability and reason-ability (you know exactly what to expect when opening/debugging a class), smaller tests, less fragility (making changes to a class has limited impact), independent deployability.

Choosing between DDD and more integrated approaches like the one (G)Rails promotes is basically a tradeoff between suppleness in time (the ability to change one aspect of a program with minimal consequences on the codebase) and immediate productivity. Neither is right or wrong, it's just a matter of context.

Upvotes: 0

Deepak Bala
Deepak Bala

Reputation: 11185

What if we make domains extend the GenericDAO? Like User.java extends GenericDAO, which allows us to have something like this:

How do you know that the consumer of this domain model will require that method (save()) ? For example User can be used in a web service that persists the User into a database using a DAO. The same User is also sent to a web service client in a response object. Why would it make sense to package the persistence layer on the web service client ? It only confuses the web client consumer since save() does not make sense there.

Just wanted to know if there are any disadvantages why people not use it this way?

From my perspective it is a separation of concerns. A User is a model. It's responsibility is to represent the state of the User. A UserDAO is part of the persistence layer. It's responsibility is to persist the model into a persistence store (such as a database). By mixing the two you couple the functionalities tightly.

Upvotes: 1

Related Questions