private override

25Feb/091

Making the ‘using’ statement, more usable

I've felt the pain of having the using statement not being able to return a value before, and just chalked it up to a limitation of the language.

I never considered trying to find a better way, and usually ended up with something like:

void DoSomething()
{
    XmlDocument xml = new XmlDocument();
    using(var reader = new StreamReader(@"c:\somexmlfile.xml"))
    {
        xml.Load(reader);
    }

    // do something useful with xml
}

or

void DoSomething2()
{
    XmlDocument xml = new XmlDocument();
    using( var reader = new StreamReader( @"c:\somexmlfile.xml" ) )
    {
        xml.Load( reader );
        // do something useful with xml
    }
}

Neither of which particularly suited me. Because

  • First example: Declaring the variable outside the scope of the block feels weird
  • Second example: Performing whatever operation inside the using block, means the file (or other resource) doesn't get released until the operation has completed.

After Shawn mentioned something about this at his Indy Alt.Net Clojure talk, I started thinking about it a little bit, and then I had a real need for it (again), and decided to come up with something better.  Turns out what I wanted was blatantly simple.

TResult UsingReturn(TDisposable toUse, Func func)
    where TDisposable : IDisposable
{
    using (toUse)
    {
        return func(toUse);
    }
}

Now the above example turns into:

void DoSomething3()
{
    var xml = UsingReturn( new StreamReader( @"c:\cdf.xml" ), reader =>
                {
                    var doc = new XmlDocument();
                    doc.Load( reader );
                    return doc;
                });
}

I'm not sure where this thing should live (e.g. some static utility class, extension method on IDisposable), or even what it should be called.  Any ideas?

11Dec/089

static reflection – Method Guards

Another bit of magic with static reflection. Refer to my last post for a little more explanation of static reflection, and a sweet implementation (IMO) of INotifyPropertyChanged using static reflection.

In the past several years, on several projects, I've seen many lines of code at the beginning of public interface methods that look like:

    public class WebServer
    {
        public void BootstrapServer(int port, string rootDirectory, string serverName)
        {
            if( rootDirectory == null )
            {
                throw new ArgumentNullException( "rootDirectory" );
            }
            if( serverName == null )
            {
                throw new ArgumentNullException( "serverName" );
            }

            // Bootstrap the server
        }
    }

I realize the need, since we don't have real DbC in .NET (yet), but I REALLY dislike this and feel it to be a pretty bad smell.  It feels unDRY, obscures essence, and I just plain don't like it. ;)

So, here is an implementation that makes it tolerable, if not enjoyable (because of the coolness of using static reflection), because I think it actually adds to the essence and overall readability of a given method.

This is what the above code can now look like:

    public class WebServer
    {
        public void BootstrapServer( int port, string rootDirectory, string serverName )
        {
            Guard.IsNotNull( () => rootDirectory );
            Guard.IsNotNull( () => serverName );

            // Bootstrap the server
        }
    }

And here is the implementation:

    public static class Guard
    {
        public static void IsNotNull<T>(Expression<Func<T>> expr)
        {
            // expression value != default of T
            if (!expr.Compile()().Equals(default(T)))
                return;

            var param = (MemberExpression) expr.Body;
            throw new ArgumentNullException(param.Member.Name);
        }
    }

Lovin it!  Hope you do too.

8Dec/087

static reflection – INotifyPropertyChanged

I'm not going to delve into the definition of static reflection here, but you'll see how it's implemented, and how I found it can help me with implementing INotifyPropertyChanged.

Now, I've never been a fan of INotifyPropertyChanged myself, mostly because it feels wet (read: not DRY).  I'm working on a WPF app at the moment, and have come to realize, if I embrace INotifyPropertyChanged, I get to take full advantage of the excellent WPF databinding story.

Here is what a normal use of INotifyPropertyChanged looks like:

    public class Person : INotifyPropertyChanged
    {
        private string _firstName;
        private string _lastName;

        public event PropertyChangedEventHandler PropertyChanged;

        public string FirstName
        {
            get { return _firstName; }
            set
            {
                if (_firstName != value)
                {
                    _firstName = value;
                    FirePropertyChanged("FirstName");
                }
            }
        }

        public string LastName
        {
            get { return _lastName; }
            set
            {
                if (_lastName != value)
                {
                    _lastName = value;
                    FirePropertyChanged("LastName");
                }
            }
        }

        private void FirePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }

Here is what the static reflection use of INotifyPropertyChanged looks like:

    public class PersonStaticReflection : NotifyPropertyChanged
    {
        private string _firstName;
        private string _lastName;

        public string FirstName
        {
            get { return _firstName; }
            set { SetProperty(()=> FirstName, ()=> _firstName, value); }
        }

        public string LastName
        {
            get { return _lastName; }
            set
            {
                SetProperty( () => LastName, () => _lastName, value, () =>
                   {
                       // do something useful here
                   });
            }
        }
    }

Doesn't that just feel DRYer?  It does to me!

There are several important pieces to note:

  • Inheriting from NotifyPropertyChanged, this is the class that holds the SetProperty method, and hides the static reflection magic.
  • We're calling SetProperty with three arguments in the FirstName property
    • first: a LINQ Expression pointing to the property we're changing
    • second: a LINQ Expression pointing to the field to backing the property
    • third: the new, incoming value
  • We're calling SetProperty with a fourth argument in the LastName property
    • fourth: an action that will get executed only if the values were different
  • The SetProperty method, is going to look at the current value of the field, and the incoming value.  If the two are different, it will assign the new value to the field, and then fire the NotifyPropertyChanged event, with the name of the property given via the first argument.  I ended up pulling this into its own class so I could use it as the layer supertype in my View Model layer. Here is the implementation:

    public class NotifyPropertyChanged : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void SetProperty < T>( Expression < Func> propExpr, Expression> fieldExpr, T value )
        {
            SetProperty(propExpr, fieldExpr, value, ()=> { });
        }

        protected void SetProperty < T>( Expression < Func> propExpr, Expression < Func < T>> fieldExpr, T value, Action doIfChanged )
        {
            var prop = (PropertyInfo)((MemberExpression)propExpr.Body).Member;
            var field = (FieldInfo)((MemberExpression)fieldExpr.Body).Member;

            var currVal = prop.GetValue( this, null );

            if( currVal == null && value == null )
                return;
            if( currVal == null || !currVal.Equals( value ) )
            {
                field.SetValue( this, value );
                doIfChanged();

                if( PropertyChanged != null )
                    PropertyChanged( this, new PropertyChangedEventArgs( prop.Name ) );
            }
        }
    }

Questions/comments/likes/dislikes? Let me know.

4Sep/084

looking for a better switch/case statement?

I find myself sometimes wishing I had a better switch/case construct in C#.

My requirements of "better" are:

  • Case statements are automatically scoped
  • I can switch on more than simple types
  • I can have custom logic for my matching criteria

But why not just use if/else if/else...?

Good question, I'm glad you asked! However, I don't have an excellent answer other than personal preference. if/else if/else is okay sometimes, but other times I have a deterministic set of conditions, and a switch type construct feels more symmetrical to me. I loves me some symmetric feeling code, it just feels cleaner somehow.

So I'll present a somewhat contrived example just so you can see what the usage looks like, then we'll see the code.

Usage


public void DoSomething()
{
	object foo = new object();
	object bar = new object();
	object baz = new object();

	Switch<object>.On(baz)
		.Case(x => x.Equals(foo), () =>
		{
			Console.WriteLine("came into foo case");
		})
		.Case(x => x.Equals(bar), () =>
		{
			Console.WriteLine("came into bar case");
		})
		.Default( () =>
		{
			Console.WriteLine("came into default case");
		})
		.Go();
}

The output from the above, is as you'd expect, the default case, since baz wasn't equal to foo or bar.

Implementation


public class Switch<T>
{
	private T _target;
	private List<KeyValuePair<Predicate<T>, Action>> _cases;
	private Action _default;

	public static Switch<T> On(T target)
	{
		return new Switch<T>(target);
	}

	public Switch(T target)
	{
		_target = target;
		_cases = new List<KeyValuePair<Predicate<T>, Action>>();
	}

	public Switch<T> Case(Predicate<T> @case, Action action)
	{
		_cases.Add(new KeyValuePair<Predicate<T>, Action>(@case, action));
		return this;
	}

	public Switch<T> Default(Action action)
	{
		_default = action;
		return this;
	}

	public void Go()
	{
		foreach(var @case in _cases)
			if (@case.Key(_target))
			{
				@case.Value();
				return;
			}
		if (_default != null)
			_default();
	}
}

The only part I don't really like is having to kick it off with the Go() at the end. Any ideas for a better way to kick it off, or at least a better name for it (instead of Go).

Feedback? Ideas?

Update

Paul had a great idea a couple great ideas (see comments) on how to get rid of the Go() at the end, and to force Default to only appear at the end. Here is the new implementation. Usage is the same, just remove the Go().


public class Switch<T>
{
	private T _target;
	private bool _alreadyMatched;

	public static Switch<T> On(T target)
	{
		return new Switch<T>(target);
	}

	public Switch(T target)
	{
		_target = target;
		_alreadyMatched = false;
	}

	public Switch<T> Case(Predicate<T> @case, Action action)
	{
		if (!_alreadyMatched && @case(_target))
		{
			_alreadyMatched = true;
			action();
		}
		return this;
	}

	public void Default(Action action)
	{
		if (!_alreadyMatched)
		{
			_alreadyMatched = true;
			action();
		}
		return this;
	}
}
Tagged as: , 4 Comments