开发者

Return a delegate that leaks implementation details

I have a class called MapBuilder<T> which internally uses a Dictionary<PropertyInfo,string> The class is used to quickly buil开发者_JAVA技巧d up a mapping of which properties will be proxied. The class looks like this::

public class MapBuilder<T>{
    private Dictionary<PropertyInfo, string> m_Map = new Dictionary<PropertyInfo,string>();

    public MapBuilder<T> Add<TProperty>(Expression<Func<T, TProperty>> property){
        ArgumentValidator.AssertIsNotNull(()=>property);
        var propertyInfo = Reflect.Property<T>.InfoOf(property);
        m_Map.Add(propertyInfo, propertyInfo.Name);
        return this;
    }

    public MapBuilder<T> Add<TProperty>(Expression<Func<T, TProperty>> property,string columnName){
        ArgumentValidator.AssertIsNotNull(() => property);
        ArgumentValidator.AssertIsNotNull(() => columnName);
        var propertyInfo = Reflect.Property<T>.InfoOf(property);
        m_Map.Add(propertyInfo, columnName);
        return this;
    }

    public Map Compile(){
        return m_Map.TryGetValue;
    }

So a user would use it like so::

 var map= new MapBuilder<MyClass>()
.Add(x => x.Name)
.Add(x => x.Id)
.Add(x => x.Active)
.Compile()

Which would build a map that encapsulates the 3 properties of Name,Id,Active. The problem is that the Map delegate can now leak implementation detail to an end user because they can observe the method to be the TryGetValue method of a Dictionary<PropertyInfo,string> and the target will be the private dictionary. Would you consider this a code smell?

I can wrap this in an anonymous method, but I tend to consider that bad form when a method group conversion is possible.


The level of effort involved in looking at the target and method of your Map delegate is about the same as reflecting over the fields of the MapBuilder class itself; either way, the caller can discover the private Dictionary instance.

I wouldn't worry about it from the point of view of the MapBuilder class. Reflecting over private fields would definitely be a code smell: but then it's not your responsibility, but the responsibility of the user of your class.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜