Tuesday, March 13, 2012

Should class properties each write value to database when set of have update method?

I've often deliberated about the following so I thought I would finally get some insight in to what others would do.

If I have a class which has a number of properties which relate to columns in a sql server table should I update the database when the property is set or should I allow the properties to be set and then only update the database for all properties once an update method on the class is envoked?

I assume that the second approch would be more efficient and better in performace but it does mean that when properties are set they will only be written to the database if and when the update method is called.

Here are the two examples in code - first would update when each property is set and the second example would only update the db once the update method was envoked. I have only used one property but there would many properties.

Example 1:

Public Class Employee

Private_FirstName As String
... etc, etc.

PublicProperty FirstName()AsString
Get
Return _FirstName
EndGet
Set(ByVal valueAsString)
_FirstName = value
' Code to update database
EndSet
EndProperty

... etc, etc.

End Class

Example 2:

Public Class Employee

Private_FirstName As String
... etc, etc.

PublicProperty FirstName()AsString
Get
Return _FirstName
EndGet
Set(ByVal valueAsString)
_FirstName = value
EndSet
EndProperty

... etc, etc.

Public Sub Update()
' Code to update database for all properties
EndFunction

End Class

I only update the field when I want to, so I have to call an update function. This way you can modify your employee as much as you want without any overhead to the database and then you update the database. If your doing thing in n-tier, your business layer class should not be aware of your data layer, so the update function should not be in your employee class. But all of this still depend on the spec of your application.

0 comments:

Post a Comment