design pattern for building mapping object

301 views Asked by At

I am trying to build a mapping object with pre-poulated data and trying to find best way to do it.

I am trying to achieve something like this.

public static class CodeNameMapping
    {
        private static Dictionary<string, string> _mapping = new Dictionary<string, string>();
        static CodeNameMapping()
        {
            _mapping.Add(Constants.CODE_FS, PageNames.FB_PAGE);
            _mapping.Add(Constants.CODE_MA,PageNames.MA_PAGE);
        }

        public static string GetPageNameFor(string code)
        {
            return _mapping[code];
        }
    }

Is this a good way to achieve this? Or are there any other better patterns of doing this?(I could think of factory???)

1

There are 1 answers

0
zigdawgydawg On

You could use the static initializer for a Dictionary like so:

public static class CodeNameMapping
{
    private static Dictionary<string, string> _mapping = new Dictionary<string, string>{
        {Constants.CODE_FS, PageNames.FB_PAGE},
        {Constants.CODE_MA, PageNames.MA_PAGE}
    };

    public static string GetPageNameFor(string code)
    {
        return _mapping[code];
    }

}

And, inside GetPageNameFor, you may want to make sure the key exists first.