private override

11Feb/092

Dealing with Dependencies – A Presentation on DI and IoC

I gave a presentation recently at my company (www.sep.com) on the basics of DI and IoC.  On how they are different, how they relate, why you should care, and how you can get started.

Here is the slide deck: http://jonfuller.googlecode.com/svn/trunk/presentations/dependencies/Dealing%20with%20dependencies.pptx

There isn't anything here that is new or groundbreaking, but I feel like its a decent intro with a couple decent examples.  Let me know what you think!

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.

3Oct/080

reflection

It being a day or several (depending on when this gets published) after my birthday, it seems like a good time to reflect, and to set some goals for the upcoming short-term (~year).

The list is not all about technical stuff.  It is really stemmed from some things God has laid in front of me lately.

Becoming a message

Our pastor shared a great quote with our church last weekend that really stood out to me.

...my life is my message  - Gandhi

What would my message be if someone asked me today?
What would my message be if someone asked you today?
What would your message be if someone asked you today?

I'm guessing there will be more about this coming soon.

Continuous Improvement

This area is far more about you than it is about me.  Sure, I have much to learn, have a long list of areas of which I'd like to personally continue to improve.I feel a great need to help my colleagues, help my company, and help my community.  Something tells me I'm in a unique position to make an impact on each.So here is a list of areas I'd like to improve (in to particular order):

  • Technical Breadth
  • Technical Depth
  • Leadership Skills
  • Management Skills
  • Physical Health
  • Faith
  • Creativity
  • Being a better husband
  • Brewing better coffee
  • ...

Back to Basics

I'm a firm believer in fundamentals.  I'd like to re-explore what the core fundamentals of the industry are, and find out where I need to brush up/start over/start (for the first time).

Okay... enough for now.  Stay tuned.

17Sep/081

a generic one-to-one mapping class

Another "tip/trick" style post, but thought it may prove useful to someone (or so I can find it again later!)...

Sometimes I find myself needing to map instances/values of one type to another.  For example, on my current project we have an enumeration in our communications layer, and a VERY similar one in the domain layer.  The reason for this is so we don't have to be referencing the communications layer version all over in the domain code.  So, there is naturally a one to one mapping between these enumerations.

Consider the following enumerations:

enum Polygons
{
    Triangle,
    Rectangle,
    Pentagon,
    Other
}

enum NumSides
{
    Three,
    Four,
    Five,
    More
}

This is the code I usually write to solve this problem:

private Polygons MapShapes( NumSides sides )
{
    switch( sides )
    {
        case NumSides.Three:
            return Polygons.Triangle;
        case NumSides.Four:
            return Polygons.Rectangle;
        case NumSides.Five:
            return Polygons.Pentagon;
        case NumSides.More:
            return Polygons.Other;
        default:
            throw new NotSupportedException(
                string.Format( "Mapping to Polygons from NumSides value {0}
                    is not supported", sides.ToString() ) );
    }
}

private NumSides MapShapes( Polygons polygon )
{
    switch( polygon )
    {
        case Polygons.Triangle:
            return NumSides.Three;
        case Polygons.Rectangle:
            return NumSides.Four;
        case Polygons.Pentagon:
            return NumSides.Five;
        case Polygons.Other:
            return NumSides.More;
        default:
            throw new NotSupportedException(
                string.Format( "Mapping to NumSides from Polygons value {0}
                    is not supported", polygon.ToString() ) );
    }
}

It turns out we had 3 said enumerations.  So picture the above, copied 3 times.  This thing was just begging for abstraction!

I came up with a Generic (proper) Map class that you can add mappings to and retrieve the corresponding mapped value of the other type... both directions.  Here is the implementation:

public class Map
{
    private Dictionary _oneToTwo;
    private Dictionary _twoToOne;

    public Map()
    {
        _oneToTwo = new Dictionary();
        _twoToOne = new Dictionary();
    }

    public Map Add( Type1 value1, Type2 value2 )
    {
        _oneToTwo.Add( value1, value2 );
        _twoToOne.Add( value2, value1 );
        return this;
    }

    public Type1 this[Type2 value]
    {
        get
        {
            if( !_twoToOne.ContainsKey( value ) )
            {
                throw new NotSupportedException(
                    string.Format( "Mapping from type {0} to type {1} with
                                    value {2} is not defined",
                        typeof( Type2 ).Name,
                        typeof( Type1 ).Name,
                        value.ToString() ) );
            }
            return _twoToOne[value];
        }
    }

    public Type2 this[Type1 value]
    {
        get
        {
            if( !_oneToTwo.ContainsKey( value ) )
            {
                throw new NotSupportedException(
                    string.Format( "Mapping from type {0} to type {1} with
                                    value {2} is not defined",
                        typeof( Type1 ).Name,
                        typeof( Type2 ).Name,
                        value.ToString() ) );
            }
            return _oneToTwo[value];
        }
    }
}

And, here it is in action:

Map<NumSides, Polygons> shapeMap = new Map<NumSides, Polygons>()
                                    .Add( NumSides.Three, Polygons.Triangle )
                                    .Add( NumSides.Four, Polygons.Rectangle )
                                    .Add( NumSides.Five, Polygons.Pentagon )
                                    .Add( NumSides.More, Polygons.Other );

// shape1 value is Polygons.Rectangle
Polygons shape1 = shapeMap[NumSides.Four]; 

// shape2 value is NumSides.Three
NumSides shape2 = shapeMap[Polygons.Triangle];

This not only works with enumerations, but any type.  I see an extension to this possibly allowing for a default mapping, and possibly constraining Type1 and Type2 to be IComparable or something like that as well, so you can have more control over your matching than whatever the default matching behavior that the Dictionary uses is.

That's it... enjoy!

Tagged as: , 1 Comment
26Aug/083

tfs – using winmerge as your merge/diff tool

If you're used to using something like winmerge with your SCM of choice, if you wind up using TFS, the built-in diff/merge tools can leave much to be desired.

Here is how to change the tool VS 2kX uses to do diffs/merges when hooked up to TFS (note that these are my settings for using winmerge for ALL file types):

Go To: Tools/Options/SourceControl/Visual Studio Team Foundation Server/Configure User Tools

Click "Add..."
Extension:  .*
Operation: Compare
Command: C:\Program Files\WinMerge\WinMergeU.exe
Arguments: /e /wl /dl %6 /dr %7 %1 %2
Click "Add..."

Extension:  .*
Operation: Merge
Command: C:\Program Files\WinMerge\WinMergeU.exe
Arguments: /ub /dl %6 /dr %7 %1 %2 %4

The winmerge command line reference can be found here.

Tagged as: , 3 Comments
26Aug/080

tfs – error exporting queries to excel

Starting my new project in a new role, as project lead, I need to be managing things in TFS.  The UI for batching these things up is nonexistent, but there is Excel integration so you can do it all in Excel, hit save, and it all goes back to the TFS server... pretty slick I must say (I was actually in the midst of writing such a tool when I realized this functionality already existed OOB).

However, the first time I tried to use this functionality... BLAM, I get smacked with this:

TF80042: The document cannot be opened because you do not have Microsoft Excel 2003 or later, or one of its components installed. For more information, see the Team Foundation Installation Guide.

Isn't that teh suck?

Anyways, there is a sweet write-up on how to fix it here: http://blogs.microsoft.co.il/blogs/srlteam/archive/2007/07/17/Error-when-trying-to-export-queries-to-Excel.aspx.

Thanks Elad!

Tagged as: , , No Comments
22Aug/081

Going Medieval on Your App with Castle MonoRail – Indy ALT.NET

So last night I gave a talk at Indy ALT.NET on Castle MonoRail.  It was really just a sort of intro to MonoRail type of deal, but the cool part was that we held a Dojo after I got done jabbering.

We ended up building a Poll Generator for our dojo activity.  We almost got done in the 45 minutes or so that we dojo'd.  It was a pretty fun activity, and I'd like to do it again sometime soon.

Also, this was really my first public speaking engagement to our technical community, and let me say it was a blast.  Everyone had great things to say, and many great questions were asked too.

I set up a google code repository so you can grab my slidedeck and grab the source for our dojo activity and my demo app.

Maybe next time I'll post before the talk, so I can let people know about it.

Thanks guys for all the great feedback, and thanks to my wife for understanding why I wasn't spending any of my evenings with her this week!

22Aug/080

singly implemented interface… addendum

Wowza!  So I've begun reading LosTechies (tons of great content, highly recommended!), and came across a passage today from Jimmy Bogard, who says what I feel, but what I couldn't get out of my head:

On a sidenote, it always bothered me when people say that an interface with one implementation is a design smell.  No, an interface is used to expose a contract.  Interfaces communicate design intent, far better than a class might.

Exactly!

Tagged as: , No Comments
16May/081

singly implemented interface… why/why not

So one of the things I've noticed since I've been at my new place of employment, is that people are passionate about their code!  I love it!  I have always been, and its great to be in a place where everyone else is as passionate about it as I am.

Onto the issue at hand.  Along with passion, comes strong opinions (of course).

Statement: I always want to create an interface for any service or class that collaborates with other services or classes.

Why?

Testability.

IMO (I've got one too!), testability is THE first class citizen (second only to working, value-adding software).

Having an interface on any collaborating service provides me the ability to (at least):

  • TDD
  • Test after the fact
  • Swap in a new implementation later
  • Low-friction

Why not? (my response to each in red)

  • YAGNI - "Why do you need an interface if there is only one implementer?  We'll create the interface or base class when there is a second implementer".
    There already is a second implementer... the tests!  Nuff said. (which is a nice segue into the next point...)
  • Testability should not affect the design.
    Ahem, isn't our goal working software?  How do I know it works if I can't write tests for it?  This directly opposes the entire idea of TDD.  TDD is not so much about testing, as it is about it being a design tool.
  • Just "subclass and override".
    Have you ever read Working Effectively with Legacy Code? This is the epitome of a legacy code technique

Dear reader (I doubt there are any),

What do you think?  Are there things I missed on either side of the equation?  I want your opinions.

Tagged as: , 1 Comment