开发者

Is it better to populate an object's properties in the constructor or when the property is referenced?

开发者 https://www.devze.com 2023-03-22 14:41 出处:网络
Background: I have an object with a dozen or so properties. The object is instantiated by passing a GUID to the constructor. This GUID is a primary key used to retrieve the property values from the da

Background: I have an object with a dozen or so properties. The object is instantiated by passing a GUID to the constructor. This GUID is a primary key used to retrieve the property values from the database. Each property is stored in a separate table in the database. We are using EF4 to connect to the database.

Is it better to get all the properties at once from the database or is it better to fetch the property values from the database when the property is actuall开发者_开发知识库y used in the code? What is the recommended best practice?


I would probably change the code to pass a Guid to a static factory method, which then did the lookup, and passed the recovered entity to the constructor. That way the constructor itself doesn't have to do as much work.

In most cases I would do all this eagerly though - it's usually odd to have an object which "feels" simple, but which then does potentially expensive and fallible database lookups when you access properties. And yes, you should strive to fetch everything in one database lookup - unless one of the properties is actually a collection in itself, etc. If it's just a case of fetching simple fields from the database, it would be crazy to perform one lookup per property access - which could end up giving inconsistent data, too.


At my job we use java / hibernate to handle the db related queries. You can configure it either way - lazy fetching waits for the application to request a property, or you can populate the object's properties on the initial query.

I'm not sure of a standard; however for our application we've found that populating the properties first turned out to be much faster. Its probably worth running a handful of tests to see how your application behaves - could be very different from ours.

0

精彩评论

暂无评论...
验证码 换一张
取 消