As an object database db4o can take advantage of programming language specifics such as static modifier. Why and where should it be used?
Usually static fields are used to store enums and constants. Obviously these objects can be stored in application code only, keeping database file smaller and decreasing memory consumption at runtime. But it can be not the best option in the case when the constant (enum) value can be changed in application lifecycle: the references from all the database objects will have to be updated explicitly.
Db4o suggests another approach to keeping constant values. For a class
01/* Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com */ 02
using System; 03
using System.Drawing; 04
05
namespace Db4objects.Db4odoc.StaticFields 06
{ 07
public class Car 08
{ 09
public Color _color; 10
} 11
}
1' Copyright (C) 2004 - 2007 db4objects Inc. http://www.db4o.com 2
Imports System.Drawing 3
4
Namespace Db4objects.Db4odoc.StaticFields 5
Public Class Car 6
Public _color As Color 7
End Class 8
End Namespace
the color field can be set to Color enumeration value like that:
01public static void SetCar() 02
{ 03
IObjectContainer db=Db4oFactory.OpenFile(Db4oFileName); 04
try 05
{ 06
Car car = new Car(); 07
car._color = Color.Green; 08
db.Set(car); 09
} 10
finally 11
{ 12
db.Close(); 13
} 14
}
01Private Shared Sub SetCar() 02
Dim db As IObjectContainer = Db4oFactory.OpenFile(Db4oFileName) 03
Try 04
Dim car As Car = New Car() 05
car._color = Color.Green 06
db.Set(car) 07
Finally 08
db.Close() 09
End Try 10
End Sub
Now, when ObjectContainer is reopened and the green car is retrieved from the database, the static instances in RAM will be associated with the previously persisted instances using #bind() under the hood. So that the following check is possible:
car.color == Color.GREEN
This also means that ,if Color.GREEN constant will get another internal value (RGB(0,255,10) instead of RGB(0,255,0) for instance), all the references from the database will be associated with the new value.
Static field values are associated with their persistent identities only once, when an ObjectContainer is opened. After that they are not stored, unless the developer does it deliberately. Objects instantiation from the database does not create any more instances of static values.
Since each static field exists only once in the VM, there are no versioning, locking or multiuser access problems.