开发者

Reducing Duplicated Code

I have some code that works on the color structure like this

public 开发者_运维技巧void ChangeColor()
{
    thisColor.R = thisColor.R + 5;
}

Now I need to make a method that changes a different variable depending on what it is passed. Here is what the code looks like now.

public void ChangeColor(int RGBValue)
{
    switch(RGBValue)
    {
        case 1:
            thisColor.R = thisColor.R + 5;
            break;
        case 2:
            thiscolor.B = thisColor.B + 5;
            break;
    }
}

Now, this is something I would normally never question, I'd just throw a #region statement around it and call it a day, but this is just an example of what I have, the actual function is quite long.

I want it to look like this:

public void ChangeColor(int RGBValue)
{
    thiscolor.RGBValue = thiscolor.RGBValue;
}

So essentially the value would refer to the variable being used. Is there a name for this? Is this what Reflection is for? Or something like that... Is there a way to do this?


I'm not 100% sure if this is what you want. But with the given example, it sounds like this might be what you're after.

you might be able to use the ref keyword:

public void ChangeColor(ref int color)
{
    color += 5;
}

void SomeMethod()
{
    ChangeColor(ref thisColor.R); //Change the red value
    ChangeColor(ref thisColor.B); //Change the blue value
}


This is definitely not what reflection is for. In fact, there seem to be a number of issues here. Let's review here - you want to change the following method:

public void ChangeColor(int RGBValue)
{
    switch(...)
    {
        case ...
        case ...
        case ...
    }
}

Into something like this:

public void ChangeColor(int RGBValue)
{
    thisColor.{something-from-RGBValue} += 5;
}

The problems with this are:

  • The name of the method, ChangeColor, does not precisely describe what the method actually does. Perhaps this is an artifact of anonymization, but nevertheless it's a terrible name for the method.

  • The parameter, RGBValue, does not accurately describe what the argument is or does. The name RGBValue and the type int makes it sound like an actual RGB color value, i.e. 0x33ccff for a light blue. Instead it chooses which of R, G, or B will be set.

  • There are only 3 valid values for the parameter, and yet the range of possible values is completely unrestricted. This is a recipe for bugs. Worse, individual values are used as magic numbers inside the method.

  • But perhaps most important of all, the "clean/quick method" you are asking for is precisely the abstraction that this method purports to provide! You're writing a method that intensifies the hue, and in order to keep the method short, you're asking for... a method to intensify the hue. It doesn't make sense!

I can only assume that you want to do this because you have many different things you might want to do to a Color, for example:

public void Brighten(...) { ... }
public void Darken(...) { ... }
public void Desaturate(...) { ... }
public void Maximize(...) { ... }

And so on and so forth. And you're trying to avoid writing switch statements for all.

Fine, but don't eliminate the switch entirely; it is by far the most efficient and readable way to write this code! What's more important is to distill it down to one switch instead of many, and fix the other problems mentioned above. First, let's start with a reasonable parameter type instead of an int - create an enumeration:

public enum PrimaryColor { Red, Green, Blue };

Now, start from the idea that there may be many actions we want to perform on one of the primary colors of a composite color, so write the generic method:

protected void AdjustPrimaryColor(PrimaryColor pc, Func<byte, byte> adjustFunc)
{
    switch (pc)
    {
        case PrimaryColor.Red:
            internalColor.R = adjustFunc(internalColor.R);
        case PrimaryColor.Green:
            internalColor.G = adjustFunc(internalColor.G);
        default:
            Debug.Assert(pc == PrimaryColor.Blue,
                "Unexpected PrimaryColor value in AdjustPrimaryColor.");
            internalColor.B = adjustFunc(internalColor.B);
    }
}

This method is short, easy to read, and will likely never have to change. It is a good, clean method. Now we can write the individual action methods quite easily:

public void Brighten(PrimaryColor pc)
{
    AdjustPrimaryColor(pc, v => v + 5);
}

public void Darken(PrimaryColor pc)
{
    AdjustPrimaryColor(pc, v => v + 5);
}

public void Desaturate(PrimaryColor pc)
{
    AdjustPrimaryColor(pc, v => 0);
}

public void Maximize(PrimaryColor pc)
{
    AdjustPrimaryColor(pc, v => 255);
}

The (significant) advantages to this are:

  • The enumeration type prevents callers from screwing up and passing in an invalid parameter value.

  • The general Adjust method is easy to read and therefore easy to debug and easy to maintain. It's also going to perform better than any reflection-based or dictionary-based approach - not that performance is likely a concern here, but I'm mainly saying this to note that it certainly isn't going to be worse.

  • You don't have to write repeated switch statements. Each individual modifier method is exactly one line.

Eventually, somewhere, you're actually going to have to write some code, and I would much rather that code be an extremely simple switch statement than a mess of reflection, delegates, dictionaries, etc. The key is to generalize this work as much as possible; once you've done that and created that abstraction, then you can start writing one-liner methods to do the "real" work.


It's a bit awkward, but you can pass a property 'by ref' like this:

    int ThisColor { get; set; }

    public void ChangeColor(Func<int> getter, Action<int> setter)
    {
        setter(getter() + 5);
    }

    public void SomeMethod()
    {
        ChangeColor(() => ThisColor, (color) => ThisColor = color);
    }

This is less expensive than reflection and it's compile-time checked (with reflection, you'd have to pass a string to a GetProperty call and the string name could potentially diverge from the property name in later refactoring.)


I would tend to use a dictionary rather than what i suspect could end up being a large switch statement so if you created a

Dictionary<int,Func<int,int>> map = new Dictionary<int, Func<int, int>>();

Each item in your dictionary could take then input and return the new value

so you your method you would be able to call

        public int ChangeColor(int rgbValue)
    {
        return map[rgbValue](rgbValue);
    }

which will execute the delegate specific for the Rgb value you insert, to assign a delegate you simply add a new entry to the map

map.Add(5,x => x+5);


If I understand you correctly, you'd like to write a method that takes some symbol (or property name) and modifies the property of the structure using defined by this symbol. This isn't easily possible in C# (you could of course use reflection, but...).

You could do similar thing using Dictionary containing delegates for reading and writing the value of the property. However, that will still be a bit lengthy, because you'll need to initialize the dictionary. Anyway, the code might look like this:

var props = new Dictionary<string, Tuple<Func<Color, int>, Action<Color, int>>> 
  { "R", Tuple.Create(c => c.R, (c, r) => c.R = r),
    "G", Tuple.Create(c => c.G, (c, g) => c.G = g),
    "B", Tuple.Create(c => c.B, (c, b) => c.B = b) };

This creates a dictionary that contains string (name of the property) as the key and a tuple with getter delegate and setter delegate for each of the property. Now your ChangeColor method could look like this:

public void ChangeColor(string propName) {
  var getSet = props[propName];    
  getSet.Item2(thisColor, getSet.Item1(thisColor) + 5);
}

The code would be more readable if you used your own type with Get property and Set property instead of Tuple with properties named Item1 and Item2. This solution may be useful in some scenarios, but you still need to explicitly list all the properties when initializing the dictionary.


This might be what your looking for, you may want to add some error handling though.
It will work with any kind of property with public get; and set; methods.
And if you want to there is ways to reduce use of "magic-strings".

public static void ChangeProperty<T>(this object obj, string propertyName, Func<T,T> func)
{
    var pi = obj.GetType().GetProperty(propertyName);
    pi.SetValue(obj, func((T)pi.GetValue(obj, null)), null);
}
public void Change()
{
    thisColor.ChangeProperty<int>("R", (x) => x + 5);
}


Well, it's kind of hard to tell what's really going on since you've given a very simplified example.

But, what I'm really reading is that you want to have a method that will perform one of a number of possible modifications to local state based upon one of the parameters of the method.

Now, is the operation the same, except for what it's being done to?

Ultimately, you have to have some code that understandds that maps an input to a desired operation. How much that can be generalized depends upon how similar the actions are (if it's always 'add 5 to a property' you have more generalization options...).

Some options you have are:

  1. Write a class which encapsulates the Color struct.
  2. Use a lookup table of Actions, as suggested by Kev Hunter.
  3. Write a switch statement.
  4. Pass in a parameter which contains a virtual method which can be executed on the internal data (or just pass in an Action<> directly) - avoiding the lookup

And... that's about it, really. Which one of these makes the most sense probably depends more on your actual use case (which we don't really have a lot of info on) than anything else.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜