Friday, March 30, 2012

The Stable Dependencies Principle (SDP) and nDepend

Latin used to be the universal academic language and this probably why Latin is still in use in classical academic disciplines such as law and medicine. Particularly in medicine, even the simplest texts appears as complete gibberish to the uninitiated.
Computer science on the other is a rather young academic discipline. This is probably a reason why we don't have to deal with old luggage such as learning some old language such as Latin to learn the field.
At least this was the case until about 1994 when Robert C. Martin of Object Mentor introduced three design quality metrics in his paper OO Design Quality Metrics and when doing this decided that it was time to have some Latin in computer science as well.
  • Ca : Afferent Couplings : The number of classes outside this component that depend upon classes within this component
  • Ce : Efferent Couplings : The number of classes inside this component that depend upon classes outside this component
  • I : Instability : (Ce ÷ (Ca+Ce)) : This metric has the range [0,1].  I=0  indicates a maximally stable category.  I=1 indicates a maximally instable component.
Actually in his original paper he talked about categories, referring to Grady Booch, but he has later repeated the same metrics for components

Is the ferry coming or is it leaving?

Instability is regular english, but "Afferent and Efferent Couplings"? I can easily remember that its about incoming and outgoing couplings, but I suppose incoming and outgoing would have been to simple.
If you try to google them you will see that the most common use of afferent and efferent are as medical terms. Wikipedia defines afferent as: "Afferent is an anatomical term" and "Efferent is an anatomical term". Same story at, no references to classes and dependencies, just medicine and anatomy.

Well as I said, doctors are used to this Latin business, I am not, but I try to remember which is which by trying to remember the little Latin I do know and what these two words are composed of.
Afferent is ad- + ferre and efferent is ex- + ferre, which means roughly something along the lines of "carry to" and "carry away from". There obviously is some rule in latin that ad- before an f, becomes af-, and ex- before an f becomes ef-.
The origins of the word ferry is also ferre.
So we only have to remember that Af- is Ad-, and then we have to know that Ad means towards.

Ad-ferre - the ferry is coming

We have afferent coupling when the direction of the dependencies is going inwards, or towards our component.

Ex-ferre - the ferry is leaving, exiting the port

If we also can remember that Ef- really is Ex-, and Ex- mean "out of", we have got it. I always think of Exodus or Exit when trying to remember the meaning of Ex.

We have efferent couplings when the direction of the dependencies is going away from our component. When we are depending on something.

The Main Sequence and the Stable-Abstraction Principle (SAP)

So now that we remember what Ce, Ca and I means we can go on to the next step and look into what we can do once we know how to calculate the Instability of a component and what it means.
Well actually I have only mentioned that the Instability is related to afferent and efferent couplings, but the general idea is that this Instability number tells us something about how hard it is to change the component.

This is not to say that every component should be hard nor that all should be easy to change.
Martin writes in his 1994 paper about the main sequence, and he later refines this into the Stable-Abstraction Principle which states:
A component should be as abstract at it is stable

Although possible it is not practical to count and calculate these numbers as we are writing our code. Fortunately tools such as nDepend exist to do this job for us.

nDepend can be downloaded free of charge for use in Open Source projects and trial version is available for commercial use.

To check where your code is with respect to the Stable-Abstraction Principle and a lot of other metrics, download nDepend and start it. Then go File->New Project

Then add the assemblies you want to analyze, the easiest option is to simply select a Visual Studio solution and nDepend will locate the assemblies for you.

After you have selected the assemblies, simply hit F5 and nDepend will generate a detailed report for you which among a lot of details contains a diagram which is called "Assemblies Abstractness vs. Instability" which is exactly the same as Martins main sequence diagrams.

The Stable Dependencies Principle (SDP)

In a later article on Stability Martin introduces the Stable Dependencies Principle:


In other words the components we depend on should be harder to change than the component we are working on. We want to reduce the likelihood of needing to change our component because one of our dependencies change.
So we should check our code for this as well, this is supposed to be something that nDepend will tell us directly out-of-the-box, at least this is what the nDepend documentation says, but I haven't been able to find it.
Anyway there are ways that we can tailor the information that nDepend does provide exactly as we want.
nDepend provides us with a query language called CQL that we can use to get information about our code. It is in a syntax that bears some resemblance to SQL, but just don't be fooled into believing it is SQL, it can do a lot, but not nearly as much as you can do with data and SQL. 
If the standard report doesn't tell you what you are looking for, there are a lot of other pre-made queries you can run and you can write your own.

To get a list of the Instability values (I) of all your assemblies you can run the following CQL:
// <Name>Olavs Instability of assemblies</Name>

What we can make use of is that nDepend will output a number of XML files when it is run and we can run it from the command.
So when we have made a nDepend project, added the solution (assemblies) and added the above CQL query, then nDepend will produce XML files that we can use to do a Stable Dependencies Principle check ourselves.
To run from the command line:
Start a command prompt in the folder where nDepend is installed and execute: nDepend.Console.exe <path to the ndepend project file>

The XML output files will be in a folder called NDependOut in the same folder as the nDepend project file.
The two we are interested in are AssembliesDependencies.xml and CQLResult.xml:

The AssembliesDependencies.xml lists for each assembly the assemblies the assembly depends on and all the assemblies that depends on the assembly.
This is an example of a part of an AssembliesDependencies.xml file:

  <Dependencies_For Assembly="MyProject.UI v1.0.0.0">
      <DependsOn_Name>mscorlib v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.Web v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>System v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>MyProject.Domain v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>MyProject.Service.DataContracts v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.Web.Abstractions v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.ServiceModel v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.Configuration v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>MyProject.Mapping v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>MyProject.Services.DataContracts v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>MyProject.Preview.Model v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.Core v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>MyProject.Services.ServiceContracts v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.Web.Extensions v4.0.0.0</DependsOn_Name>
      <ReferencedBy_Name>MyProject.Web v1.0.0.0</ReferencedBy_Name>
      <ReferencedBy_Name>MyProject.CalculationService v1.0.0.0</ReferencedBy_Name>
  <Dependencies_For Assembly="MyProject.Web v1.0.0.0">
      <DependsOn_Name>MyProject.UI v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>MyProject.Domain v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>MyProject.Mapping v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.Web v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>mscorlib v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>System v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>MyProject.Service.DataContracts v1.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.Web.Extensions v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.Core v4.0.0.0</DependsOn_Name>
      <DependsOn_Name>System.ServiceModel v4.0.0.0</DependsOn_Name> 

The other file that we are interested in is the CQLResult.xml file. If you remember that we added a query for the Instabilities of assemblies and that we named it: "Olavs Instabilities.....". The result of this query will now appear in the CQLResult.xml file. There will be a lot of other results as well, but we can search for our query  by the name we gave it in the comment of the query.
This is an example of the "Olavs Instabilities of assemblies" section:

    <Query Status="Warn" Name="Olavs Instability of assemblies" NbNodeMatched="33" NbNodeTested="33" SelectionViewFileName="SelectionView_-266889740.png" KindOfNode=" assemblies">
      <QueryHtml>&lt;font color='#008000'&gt;//&amp;#0160;&amp;lt;Name&amp;gt;&lt;/font&gt;&lt;b style="color:#008000;background-color:#E6FFE6"&gt;Olavs&amp;#0160;Instability&amp;#0160;of&amp;#0160;assemblies&lt;/b&gt;&lt;font color='#008000'&gt;&amp;lt;/Name&amp;gt;&lt;br/&gt;&lt;/font&gt;&lt;font color='#0000FF'&gt;WARN&lt;/font&gt;&amp;#0160;&lt;font color='#0000FF'&gt;IF&lt;/font&gt;&amp;#0160;&lt;font color='#000064'&gt;Count&lt;/font&gt;&amp;#0160;&lt;font color='#000000'&gt;&amp;gt;&lt;/font&gt;&amp;#0160;&lt;b style="color:#000000;background-color:#FFFF99"&gt;0&lt;/b&gt;&amp;#0160;&lt;font color='#0000FF'&gt;IN&lt;/font&gt;&amp;#0160;&lt;font color='#0000FF'&gt;SELECT&lt;/font&gt;&amp;#0160;&lt;font color='#0000FF'&gt;ASSEMBLIES&lt;/font&gt;&amp;#0160;&lt;font color='#0000FF'&gt;ORDER&lt;/font&gt;&amp;#0160;&lt;font color='#0000FF'&gt;BY&lt;/font&gt;&amp;#0160;&lt;font color='#000064'&gt;Instability&lt;/font&gt;&amp;#0160;&lt;font color='#0000FF'&gt;ASC&lt;/font&gt;</QueryHtml>
        <Row Name="System.ServiceModel" FullName="System.ServiceModel">
        <Row Name="System.Web.Abstractions" FullName="System.Web.Abstractions">
        <Row Name="MyProject.Domain" FullName="MyProjectDK.DealerPortal.Domain">
        <Row Name="MyProject.CalculationService.Data" FullName="MyProjectDK.DealerPortal.CalculationService.Data">
        <Row Name="MyProject.Mapping" FullName="MyProjectDK.DealerPortal.Mapping">
        <Row Name="MyProject.Service.DataContracts" FullName="MyProjectDK.DealerPortal.Service.DataContracts">
        <Row Name="MyProject.UI" FullName="MyProjectDK.DealerPortal.UI">
        <Row Name="MyProject.Repositories" FullName="MyProjectDK.DealerPortal.Repositories">
        <Row Name="MyProject.Preview.Model" FullName="MyProjectDK.DealerPortal.Preview.Model">

So now we have two lists (xml files), the first one has all the dependency information for the assemblies and the second has the calculated Instability values for each of the assemblies.

Now we only have to combine these two lists to check if we have any assemblies that breaks the Stable dependencies principle.
I have written a small console application that will do just this. The source code for it is available at
The application is exuted from a command prompt as this: 
                        SPDChecker <path to CQLResult.xml> <path to AssembliesDependencies.xml>

And the result looks something like this:

Should you try it and should it find something in your assemblies, please be advised that even if my warning text may indicate that this is a major crisis, remember what Robert C. Martin himself wrote about his metrics:
However, a metric is not a god; it is merely a measurement against an arbitrary standard.  It is certainly possible that the standard chosen in this paper is appropriate only for certain applications and is not appropriate for others.  It may also be that there are far better metrics that can be used to measure the quality of a design. 
Thus, I would deeply regret it if anybody suddenly decided that all their designs must unconditionally be conformant to “The Martin Metrics”.  I hope that designers will experiment with them, find out what is good and what is bad about them, and then communicate their findings to the rest of us.
I agree 100% with Mr. Martin on this.
There is also a very good explanation of these two principles (SDP/SAP) in Robert C. Martins book: "Agile Principles, Patterns and Practices in C#", Prentice Hall, pages 426-435

Tuesday, March 27, 2012

Binding the View and ViewModel in a Windows Phone 7 app

I have wanted to start developing apps for Windows Phone 7 for a long time, but never gotten around to actually do it. So when a former colleague of mine started a blog series about Creating a reusable base for WP7 apps on his company blog I thought this was a great opportunity to get started. The author, Yngve Bakken Nilsen is one of the best web-developers I have ever worked with, so my expectations to this series are high.

Navigation between pages and binding of the view and viewmodel are central topics of the first two posts.
Yngve proposes to use attributes containing paths to the View on the ViewModel objects to bind the View and ViewModel. He implements methods using reflection and these attributes to look up the View given a ViewModel. Even though Yngve says in his post that "some good'ol reflection (it's not as scary as you might think)", I can't help it, I always get a bit uneasy when I see reflection and attributes containing magic strings that are used to find types. If I can avoid it I prefer to do so, and this is what this post is about.
Are there other ways to bind the View and the ViewModel while still keeping things nice and simple?

Initial architecture

Yngve builds and initial architecture as shown in the diagram below:

The App object contains a MasterViewModel object that acts as a master object keeping track of the CurrentViewModel and the CurrentPage object.

The architecture is based on an assumption that each ViewModel will have one-to-one relationship with the  View.
Having only one ViewModel per View is all fine and dandy to me, but I can see that there may be scenarios where we would like to have more than one View share the same ViewModel.
Jeremy Likness in his post Model-View-ViewModel (MVVM) Explained mentions that multiple views on a single ViewModel could be beneficial if we are to implement a wizard. A single view-model shared between the wizard pages could be nice, but for the sake of simplicity I can live with 1-to-1.

Jeremy Likness also discuss the two ways to drive the creation and discovery process. One can opt to do as Yngve has done, go from the ViewModel to the View, this is referred to as ViewModel first.

Going the other direction is called, you may have guessed it already, View first.

The simple alternative

The MasterViewModel shown above has a method Goto<T> that the View will call when it wants to navigate to a different page.
E.g. in the MainPage we will have a click handler as this:
private void GoToSubpage_Click(object sender, RoutedEventArgs e)
Which will then navigate from the MainPage to the SubPage.
The goto method will find the Uri to navigate to by looking at the attribute that should be used to decorate the ViewModel class. When it has located the Uri it will use the NavigationService on the View to navigate to the Uri.
Then after the navigation has been done and the View has changed, we handle the navigated event where we see the new Uri and from the Uri we locate the matching ViewModel and set this in the view by settings its DataContext to the new ViewModel.

A simple alternative to this is to bind the ViewModel directly to the view. If the View knows what ViewModel it should bind to it can set the DataContext in its constructor.

Simply modifying MainPage.xaml.cs like this:

    public partial class MainPage : PhoneApplicationPage
        // Constructor
        public MainPage()
            DataContext = new ViewModels.Pages.MainPageViewModel();
        private void GoToSubpage_Click(object sender, RoutedEventArgs e)
            NavigationService.Navigate(new Uri("/SubPage.xaml"UriKind.Relative));

And SubPage as this:

    public partial class SubPage : PhoneApplicationPage
        public SubPage()
            DataContext = new ViewModels.Pages.SubPageViewModel();
        private void GoToMainPage_Click(object sender, RoutedEventArgs e)
            NavigationService.Navigate(new Uri("/MainPage.xaml"UriKind.Relative));

Makes the need for both reflection and attributes go away. When we navigate to SubPage.xaml the View (SubPage) is automatically instantiated and the constructor of the SubPage class is called which will set the DataContext. The equivalent happens when we navigate from the SubPage to the MainPage.

As can be seen from the diagram above we have replaced the more subtle dependency that we had from the ViewModel to the View with a more direct and obvious dependency from the View to the ViewModel.
This is more similar to the dependencies in the Presentation Model pattern by Fowler. MVVM is a specialization of the Presentation Model design pattern.
Although I am more happy to have a dependency in this direction, and to have done away with the reflection and the attributes, I am not to happy about the View constructing the ViewModel.
Nor am I too happy about the ViewModel being created every time we navigate to the page, it means that all ViewModel state is lost every time we navigate away from the page and back.


While googling the internet for alternative solutions I saw people mentioning that they would do things similar to this:

            <pages:MainPageViewModel x:Key="ViewModel"/>
    <!--LayoutRoot is the root grid where all page content is placed-->
    <Grid x:Name="LayoutRoot" Background="Transparent">
      <views:MainPage DataContext="{Binding Source={StaticResource ViewModel}}"/>

This is supposed to bind the View and the ViewModel, but I soon figured out that this simply isn't an option for me as it would not be very different from the "Simple alternative" I just presented. Same drawbacks as already mentioned in previous discussion above that the ViewModel can't have constructor parameters. It is still the view constructing the viewmodel and still a very hard binding from the View to the ViewModel.
Finally I couldn't make it work, adding the above xaml would cause errors, and since I didn't like the solution anyway I didn't bother to try figure out what was wrong.


Managed Extensibility Framework could provide some of the functionality that I am looking for, but sadly it seems to not be supported for Windows Phone 7 because of missing features in the base class libraries available for Windows Phone 7 applications. Damon Payne has made an unofficial MEF-for-Windows-Phone-7, but I suppose for those of us who aren't black belt Windows Phone 7 hackers yet, there may be other options that will make the learning curve a bit easier.


Jeremy Likness has published the Ultra Light MVVM for Windows Phone 7 micro framework.
It does View-first binding of the View and the ViewModel in addition to a number of other features.
It implements the binding using a "homegrown" servicelocator, which will be called from the View constructor.

To use UltraLight we need to download and build the 8 classes and 6 interfaces that are the Ultra Light framework.

The views now should look as this:

    public partial class MainPage : PhoneApplicationPage
        // Constructor
        public MainPage()
        private void GoToSubpage_Click(object sender, RoutedEventArgs e)         {             NavigationService.Navigate(new Uri("/SubPage.xaml"UriKind.Relative));         }     }

    public partial class SubPage : PhoneApplicationPage
        public SubPage()
        private void GoToMainPage_Click(object sender, RoutedEventArgs e)
            NavigationService.Navigate(new Uri("/MainPage.xaml"UriKind.Relative));

The BindToViewModel method is an extension method that among other things will find the ViewModel class implementing the specified ViewModel interface and then attach this to the View by setting the DataContext property of the LayoutRoot object to the located ViewModel object.

For this to work the map between ViewModel interfaces and the ViewModel classes must be registered. This will be done in the application launched event handler of the App object:

      private static void _RegisterViewModels()
            UltraLightLocator.Register<IMainPageViewModel>(new MainPageViewModel());
            UltraLightLocator.Register<ISubPageViewModel>(new SubPageViewModel());
        // Code to execute when the application is launching (eg, from Start)
        // This code will not execute when the application is reactivated
        private void Application_Launching(object sender, LaunchingEventArgs e)

The final requirement is that all the ViewModel classes must implement an interface and they have to inherit from the framework class called BaseViewModel. The BaseViewModel class has an abstract property called ApplicationBindings which we also are required to implement.
Haven't figured out exactly why this is, but I may be using the framework wrong on this point.

        /// <summary>
        ///     For pages, the list of commands to bind to application bar buttons
        /// </summary>
        public override IEnumerable<IActionCommand<object>> ApplicationBindings
            get { return new IActionCommand<object>[0]; }

In my opinion the Ultra Light framework looks promising as a starting point for doing Windows Phone 7 development. It's not too big or complex while still providing what seems to be a number of useful features.


Caliburn.Micro is a small framework that can be used for both WPF, Silverlight and Windows Phone 7 applications. Caliburn.Micro is a bit larger than Ultra Light, about 50 classes, but I believe it has more functionality. It comes with full source, which will by default be a part of your project. It is distributed under the MIT license.  It is built by Rob Eisenberg who presented a lot of the principles that Caliburn.Micro is based on in his talk Build Your Own MVVM Framework at MIX10.
I have watched the MIX10 video, but I haven't got much time to play with this framework yet, but so far it seems to be pure awesomeness!

To create a caliburn.micro WP7 app we must first download the zip file containing three folders

In the templates folder you will find the three project templates zip files, one for each of the supported platforms. There's also a readme.txt file there describing exactly what you need to do.
After you have copied the to the right folder you can fire up Visual Studio and you should now have a new project type available, select this and you will get a project with all the required files and you are good to go.

Look mum, no code behind!

In the figure above you can see my complete Visual Studio Solution that implements the same application as Yngve did in his blog posts. If you look at the the two views, MainPage.xaml and SubPage.xaml, you will notice that there is no code-behind. There's nothing special in the xaml file either, same as we have had in the previous examples.
All the code is in the ViewModel class

    public class MainPageViewModel 
        private INavigationService NavigationService { getset; }
        public MainPageViewModel(INavigationService navigationService)
            Title = "Kick Ass";
            NavigationService = navigationService;
        public string Title { getprivate set; }
        public void GoToSubpage()
            NavigationService.Navigate(new Uri("/SubPage.xaml"UriKind.Relative));

The ViewModel can be wired up with a NavigationService if we want to do navigation as shown above.

There is also a automatically generated file called AppBootstrapper. This is where we need to register our ViewModel classes. So for our little demo app that has two pages which we can navigate between we just need to register our two ViewModel classes and we are done.

There are no reference in the ViewModel to the View. I haven't dived enough into the details to explain exactly how the binding of the View and ViewModel works, but it is based on convention, and it simply works.
It of course has to be based on some sort of reflection, but I don't have to introduce any clutter like attributes or anything into my classes. Further it is driven by very natural conventions. I name the classes as I think I should do anyways and that's it. The ViewModel class is named ending with "ViewModel", which now tells both me and Calliburn that this is the ViewModel for the View that has the same name, except the ViewModel postfix. Furthermore, the Caliburn.Micro comes with a default IoC container, but the framework is configurable. If I somewhere down the line decides that I don't like the default container, I can plug in a different one.

The programming by convention is really used all over this framework, and to me this looks as having been done with great success.
If you look again at the MainPageViewModel above you will notice the GoToSubpage() method.
Then look at this snippet from the MainPage.xaml.

As you will notice, the button has the same name as the method in the ViewModel. That is all we need to do. When the user clicks this button, the GoToSubpage method in the ViewModel will be called and we can navigate to the next page, or whatever we want to do when the user clicks our button. Awesome!

The Caliburn.Micro is ViewModel-first, but it still can have multiple view for a single ViewModel. There's an eplanation of how they do it at the Caliburn.Micro codeplex site in the section Multiple Views over the Same ViewModel.
If you want to read more on Caliburn there's quite a lot more on the codeplex site for Caliburn.Micro Caliburn documentation.

A list of links to stuff I have read when researching this post:

And I haven't forgotten about the Wix project template, its coming, I just had to check out WP7 first :-)