开发者

Avoiding use of switch case

I've a following method "Test" which accepts a params list:

Public void method Test(params double[] list]
{
 Vols vol= new Vols();
//Fill the object based on the input list and
//pass this vol to other private method for further processing
}

Inside this method, am using a custom business object called Vols defined as follows:

public class Vols
{
    private double _vol09;
    private double _vol05;
    private double _vol01;

    public Vols()
    {
    }


    public double Vol09
    {
        get { return _vol09; }
        set { _vol09 = value; }
    }


    public double Vol01
    {
        get { return _vol01; }
        set { _vol01 = value; }
    }


    public double Vol05
    {
        get { return _vol05; }
        set { _vol05 = value; }
    }
} 

The user of method "test" can pass in values as: test(0.1,0.9);

So, 开发者_如何学JAVAdepending on the input passed, I want to set only the corresponding property in the business object "Vols"....ie. in this case , properties Vol01 and Vol09 would be set in the method "test". Is there any way to do this so that I can avoid a switch case inside the method?

This would be possible using reflection...but since reflection is expensive, is there any other approach I can make use of?Also, shall I use switch-case statement or reflection here wrt good coding practices?

Thanks.


It would be more readable if you used an object initializer...

var test = new Test() { Vol01 = 0.1, Vol09 = ... }

Your constructor can construct the default business object and your property setters can call the corresponding property on Vols.

It also might make sense to use a fluent interface which is always a good choice when there is complex, variable, constructor setup...

var test = new Test().WithVol01(0.1).AndIntentRevealingName();

or, just inject the business object...

var test = new Test(new Vols(...setup how I want it tested...));

And in C# 4.0, you can use named parameters, all the cool kids are doing it...

var test = new Test(vol01: 0.1, ...);

Reflection is overkill, and I wouldn't be worrying about performance. I would be worrying if my test cases clearly revealed intent.


Should be possible to solve using reflection


You can't switch on a variable of type double in C#, and I would avoid reflection if possible.

Your code doesn't make it clear what value you are actually going to store in the VolXX properties. They are of type double, would the Vol09 property only ever store the value 0.9?


If possible I'd rework the Vols class. Here's one idea...

public class Vols
{ 
    private List<double> _vols = new List<double>();

    public void AddVolume( double volume )
    {
        _vols.Add( volume );
    }

    public void GetVolume( int index )
    {
        return _vols.ElementAtOrDefault( index );
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜