开发者

What is the best way to support new property in legacy code

I have a architecture question about legacy. For example I have a class that using everywhere in proj开发者_运维技巧ect. Projects don't have any Unit Tests

 public class LegacyObject 
    {
      public Dictionary<string, string[]> MyLegacyProperty { get;set;} 
    } 

I need to change dictionary type to other type for example IEnumerable<KeyValuePair<TKey, TValue>>. What is the best way to change it and don't change the part of code where dictionary MyLegacyProperty using.


Well, Dictionary<T,U> does implement IEnumerable<KeyValuePair<T,U>>, so anything that wants to use the IEnumerable could reference the Dictionary property and it would work. Since you want to make that change, I'm assuming you want to do something that a Dictionary doesn't allow, duplicate keys, perhaps.

If the replacement property can be converted to a Dictionary, I'd do something like this. Have you old property sitting next to your new property, and deal with conversions in the old property's getter and setter. Note that this pattern will fail if the use case for MyLegacyProperty is to retrieve it, modify it, and not set it back; you'll need to do something akin to ObservableCollection in that case. (Is there an ObservableDictionary?)

public class LegacyObject 
{
    public Dictionary<string, string[]> MyLegacyProperty
    {
        get { return ConvertMyNewProperty(); }
        set { this.MyNewProperty = ConvertMyLegacyProperty(value); }
    }

    IEnumerable<KeyValuePair<string, string[]>> MyNewProperty { get; set; }
}

If the replacement property can't be converted to a Dictionary, then you're talking about making a real change to the external interface of your class. I don't believe there's any substitute for biting the bullet, and making the change with no backward compatibility. The only tip I can give you is to make the new property have a different name from the old one: You'll be able to use Find In Files to find the code you need to change, and it will make it so the compiler errors you get are clear and unambiguous.


If you can create a new property with a new name, you could mark the old one as [Obsolete] and slowly migrate your code base to use the new property, until there're no references to the old one and you can delete it.

If you must use the old property name, and if the property is only used within one solution in Visual Studio, you can use the renaming refactoring and change the name to something like MyLegacyProperty_Old and then create the new property with the old name.

In either case, it's a good idea to write some unit tests for your class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜