The object initializer syntax introduced in C# makes it easy to work with "configuration" type objects.
public class TemperatureSetting { public float Value { get; set; } public float Variance { get; set; } public float Threshold { get; set; } } // ... var settings = new TemperatureSetting { Value = 104f, Variance = 0.6f, Threshold = 1.2f };
The code is easy to read, but, it becomes a bit trickier if you want some additional features from the class.
and
There are a few ways to solve the problem. One approach is to hide the property setters and provide a non-default constructor.
public class TemperatureSetting { public TemperatureSetting(float value, float variance, float threshold) { //... } public float Value { get; private set; } public float Variance { get; private set; } public float Threshold { get; private set; } }
However, this approach makes construction difficult to read, unless you define variables for each value to give them a name.
var settings = new TemperatureSetting(104f, 0.6f, 1.2f); // or var value = 104f; var variance = 0.6f; var threshhold = 1.2f; var settings = new TemperatureSetting(value, variance, threshhold);
Fortunately, C# 4.0 gives us named arguments - it's the best of both worlds.
var settings = new TemperatureSetting( value: 104f, variance: 0.6f, threshold: 1.2f );
All this code needs is an extra { and } and we can put a .js extension on the file …
Comments
I like old-fashioned constructors, because intellisense makes finding out the parameters easy enough when writing the code, and F12 or mouse-over-tool-tip when reading is fine. I guess that's what I'm used to. Maybe in time I'll warm to the javascript-esque named arguments way in time.
method("abc", null, null, null, null, null);
Understandable in this situation, but not a fan otherwise.
Don't clutter my code repository (and the typing time) to regurgitate back what Intellisense already told me.
My 2 cents.