Posted By: dcuccia | May 26th @ 10:37 PM
page 1 of 1
Comments: 3 | Views: 530
Hi all,

I write a lot of code to control hardware (cameras, projectors, etc), and find myself frequently using the following pattern:

// Instantiate the class and the physical piece of hardware
Hardware h = new Hardware();

// Get settings from the user
HardwareSettings settings = GetSettingsFromGui();

// Set all parameters in an Initialize function
h.Initialize(settings);

The point of separating Initialize() is that I want to be able to change a piece of hardware's settings repeatedly w/o actually shutting it down.

Since this is a common pattern for me, I was just about to write an IInitializable interface, so that all my hardware could be spun up with the same code.

Is this a common pattern (eg. long-running db connections or something)? Is there a similar interface or pattern in the .NET BCL that already exists?



stevo_
stevo_
Casablanca != Manchester
I'm not sure what the interface would add? other than being able to standardize the settings object that hardware takes?

If you are looking for something more about convenience, perhaps you could look into a helper class to do generic property initialization?

HardwareInitializer.Initialize(h, settings);

You could even extend the fluidity of this call if you use C# 3.0, and change the Initialize method to target the base of Hardware (IHardware or HardwareBase).. this way you can say:


h.Initialize(settings);

When the hardware class doesn't even carry an Initialize method, additional to this, I believe you could probably write an Initialize method on specific Hardware implementations, and the compiler will probably look for instance methods first before extension methods..

Thus you get a somewhat loose 'override' system..
stevo_
stevo_
Casablanca != Manchester
Yes you would need to cast, so again its a loose override, theres no real override mechanic applied.

Alternative to that, you could well have an interface to specify overriding the initialization.. you util class would work against IHardware (for example), but it could check: is IHardware also ISelfInitializing ? if so, it could call the self initializing method described by self initializing..

The concept behind it was that it seemed you wanted a convenience method, otherwise a standard entry point doesn't really add any real convenience other than you setting yourself a constant pattern of initialization..

The initialization helper you would design to be smart, and cover as many scenarios as sensible, but the other interface would allow you to specify specifically designed initialization scenarios..

This way, you always initialize IHardware via an extension method (or directly via the helper class).. and the right route is taken to if the initialization is automatic, or via the 'manual override'..
page 1 of 1
Comments: 3 | Views: 530