HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Is there a better name for this class?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thisbetternameforthereclass

Problem

I need a version of the mvc RouteValueDictionary that I can chain Add calls to, ie:

new RouteValueDictionaryExtended()
        .AddValue("controller", "Home")
        .AddValue("action", "Index")
        .AddValue("id", 3)


Is there a more description name I can use for this instead of just "Extended"?

public class RouteValueDictionaryExtended : System.Web.Routing.RouteValueDictionary
    {
        public RouteValueDictionaryExtended() : base() { }
        public RouteValueDictionaryExtended(object values) : base(values) { }
        public RouteValueDictionaryExtended(System.Collections.Generic.IDictionary dict) : base(dict) { }
        public RouteValueDictionaryExtended AddValue(string key, object obj)
        {
            var newDict = new RouteValueDictionaryExtended(this);
            newDict.Add(key, obj);
            return newDict;
        }
    }

Solution

I would actually recommend you to use the (Constructor) Builder pattern if you are only doing this for easier object initialization:

public class RouteValueDictionaryBuilder
{
    private List> values_ = new List>();

    public RouteValueDictionaryBuilder WithValue(string key, object obj)
    {
        values_.Add(Tuple.Create(key, obj));
        return this;
    }

    public RouteValueDictionary Build()
    {
        var dict = new RouteValueDictionary();
        foreach (var value in values_)
        {
            dict.Add(value.Item1, value.Item2);
        }
        return dict;
    }
}


To use:

var dict = new RouteValueDictionaryBuilder()
    .WithValue("controller", "Home")
    .WithValue("action", "Index")
    .WithValue("id", 3)
    .Build();


This avoids the higher coupling (inheritance) between the dictionary and its subclass, which is there only to help with initializing the dictionary.

Code Snippets

public class RouteValueDictionaryBuilder
{
    private List<Tuple<string, object>> values_ = new List<Tuple<string, object>>();

    public RouteValueDictionaryBuilder WithValue(string key, object obj)
    {
        values_.Add(Tuple.Create(key, obj));
        return this;
    }

    public RouteValueDictionary Build()
    {
        var dict = new RouteValueDictionary();
        foreach (var value in values_)
        {
            dict.Add(value.Item1, value.Item2);
        }
        return dict;
    }
}
var dict = new RouteValueDictionaryBuilder()
    .WithValue("controller", "Home")
    .WithValue("action", "Index")
    .WithValue("id", 3)
    .Build();

Context

StackExchange Code Review Q#4170, answer score: 7

Revisions (0)

No revisions yet.