Lets say that one has a class like Person that has associated with it some default settings implemented in a Setting class. Those settings might be things like “Default Title” or “First Name Required”. Correspondingly, other classes like an Address class might also have some default settings. The Setting class persists each setting into a persistent store.
Should one implement a static method in each class like “SetDefaults()” that contains these settings so that an external method can call SetDefaults() on each object type? e.g. Person.SetDefaults() and then Address.SetDefaults()?
Or is there some better object oriented way of doing this?
[Update: this can’t be in the constructor because SetDefaults() should be called from an external class at a particular point in time, rather than each time the object is constructed.]
I can’t think of many occasions where defaults are truly spanning… given all the different use-cases that an object may go through (not least, things like deserialization – which could end up setting the defaults even though that isn’t what was intended).
One option here is IoC; IoC containers like StructureMap have the ability to set properties after initialization, and that is then abstracted from the calling code.
Another option might be some kind of template instance (static), that instances can copy values from. But I think this is risky in a few scenarios. You also get problems if different threads (perhaps requests on a web-server) need different defaults.
[ThreadStatic]isn’t a good option (although it is an option).Another option (that provides the greatest flexibility) would be to provide a user-settable factory… perhaps via a delegate or event mechanism – but I struggle to see why you might want this scenario. It isn’t one I’ve seen very often…
re update: if it is only used by the external class; could it perhaps use something like an extension method (rather than the
Personclass having to know anything about this):Since it sounds like the original
Personclass doesn’t care aboutSetDefaults, this divorces the logic fromPersonneatly.