Friday, May 18, 2012

Parameters: The Minimal C# Singleton Edition

Why argue with it? I replaced the previous example with real code. I think the result below is very modular. It is now trivial on how the Parameter class below is replaceable by any other module that implements the Program.Parse() action. This version only stores the key/value like pairs.

I thought of several more advanced versions. There was one that searches for more attributes that specify parameters keys and the code that handles them. There was also one that uses the stored entries and adds them to the background task. In both cases, any validation and further code for each parameter exists outside the class below in other modules.

After this point, you can see we simplified C++'s singleton paradigm with C#'s "sealed" keyword and the Program.Singleton attribute for private instantion.

Note the regular-expression matches “--key=value” and “--option” style parameters, and it accepts “/” instead of “--” for POSIX and DOS style parameters.

Related Posts: Part 1 2 3 4


using System.Collections.Specialized ;
using System.Text.RegularExpressions ;
using System.Diagnostics ;
using System.Collections ;
using System;

namespace Application
    {
    [Program.Singleton]
    public sealed class Parameter
        {
        static StringDictionary parameter = new StringDictionary() ;

        private Parameter()
            {
            Program.Parse       += Parse ;
            }

        ~Parameter()
            {
            Program.Parse       -= Parse ;
            }
     
        static Parameter()
            {
            #if DEBUG
                parameter.Add( "debug",  "true" ) ;
            #endif
            }

        static public void Parse( string[] args )
            {
            foreach( string s in args )
                {
                Match m = Regex.Match( s, @"^(-{1,2}|/)((?\S+)=(?.+)$|(?\S+)[^=]\s*$)" ) ;
                if( ! m.Success )
                    {
                    Debug.WriteLine( "Invalid Parameter: {0}", s ) ;
                    continue ;
                    }
                Group o = m.Groups[ "option" ] ;
                Group k = m.Groups[ "key"    ] ;
                Group v = m.Groups[ "value"  ] ;
                if( ! String.IsNullOrEmpty( o.Value ) )
                    parameter[ o.Value ] = "true" ;
                else
                    {
                    parameter[ k.Value ] = v.Value ;
                    }
                }
            }
         
        static public string Value( string key )
            {
            return parameter[ key ] ;
            }
        }
    }