Domanda

I'm building a new application and can't decide which way to go on this question.

Should the database data oriented classes build themselves from the database with methods like:

class Foo 
{
    public buildYourselfFromDatabaseForID(...)
    //and overloading the constructor etc.
    public commitYourselfToTheDatabase();
}

or should I build a database management class / factory that will handle all the SQL and build the objects for me, such as:

Foo var = dbManager->createMeAFooFromID(id);
// Make some changes to var

dbManger->commitChangesToFoo(var);

I've worked on projects doing it both ways before, but can't really decide which way to go on this new project and wondered what the general consensus is today?

I mean their are advantages and disadvantages to both ways, but what is the more commonly adopted approach on this? Are their any established patterns that you could point me towards?

È stato utile?

Soluzione

Having an entity directly contact the database is a violation of separation of concerns - it means that the class is doing, in addition to its own job, some database work, which is not its concern.

Have a factory/builder instead.

A common way to hidrate entities from the database these day is through an ORM - such a library mediates between the database and your object model and deals with all database interactions on your behalf. Examples of ORMs are Entity Framework, nHibernate, Dapper and more.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top