Thursday, 22 August 2013

Improving code quality by using NDepend

Over the past few years I’ve been using many of the tools included with Visual Studio to analyse my code. This has included running code metrics, examining test coverage, and undertaking performance analysis. However, for my money the tools that are baked into Visual Studio don’t really go far enough. While they are continuously improving there are also quite a few gaps in the data they’ll provide to you, and it’s not always a trivial task to translate that data into improved code quality. Enter NDepend.

NDepend is a static analysis tool designed to improve code quality by using code metrics and enforcing a series of rules. It can be used as a stand alone tool, integrates with Visual Studio, and also can integrate with your build process so that you can be regularly advised of the NDepend analysis results. There are all kinds of features in the tool including viewing dependency graphs, running code metrics, and running custom queries on your code. For a full list you should see here.

When you run the standalone tool you can create/open an NDepend project, analyse a code base, or compare two versions of a code base. Once you’ve analysed your code base you’re presented with a detailed screen of results.

image

You can examine a dependency graph and dependency matrix, which both allow you to detect dependency cycles between components (NDepend can also suggest the best way to remove a particular dependency cycle). The metrics view presents a graphical view of your chosen metric applied to your chosen level (field, method, type, namespace, assembly). NDepend includes a whole series of code metrics, related to code organization, structure, quality, and coverage, which you can use to improve your code quality.

However, the most useful and powerful feature to me is CQLinq which gives you the ability to query your code using LINQ-style queries. For example, you can run CQLinq queries to check:

  • The classes that implement a particular interface.
  • Which methods could have a more restricted visibility.
  • Which methods are not covered by unit tests.
  • That overrides of Method() call base.Method().
  • Whether the UI layer directly uses specific types.
  • Whether your objects are immutable and pure.

NDepend comes with 200 queries, spread over 18 categories including code quality, design, architecture and layering, dead code, visibility, purity, and naming conventions. You can use all the existing queries as is, or adapt them for your own needs. You can also write new CQLinq queries to check/enforce your own criteria. When you select a query category you are presented with a list of queries contained within the category.

image

When you select a particular query it immediately executes, displaying the results in a docked window. The code for the query is also shown, enabling you to customise it as required. For instance, when the “Methods that could have a lower visibility” query is executed, you are presented with a list of potentially offending methods, their current visibility, and a suggested lower visibility. Selecting the offending method opens it in Visual Studio where you can change its visibility. This is a very efficient way of performing such a task in comparison to scrutinising visibilities manually.

There’s all kinds of other features available in NDepend, far too many to list here in fact. So if you are in need of a static analysis tool it’s well worth taking a look at it. It’s easy to use, the CQLinq feature makes it very powerful, and it goes a lot further than any of the tools included with Visual Studio. Check it out!

Monday, 12 August 2013

Event subscription filtering using Prism for the Windows Runtime

Previously I’ve blogged about how to perform event aggregation using Prism for the Windows Runtime. When a publisher invokes the PubSubEvent<TPayload> class’s Publish method the system will run all actions that have been registered by the PubSubEvent<TPayload> class’s Subscribe method. Subscribers can control how the actions run, and use weak references by default. Therefore registering a subscription action does not add a reference to the subscriber. For more info about event aggregation see Communicating between loosely coupled components in AdventureWorks Shopper.

In this blog post I’ll extend the sample app to include event subscription filtering, so that an event subscriber callback is only executed when a filter predicate returns true.

Implementation

A subscriber may not need to handle every instance of a published event. In this case, the subscriber can use a Subscribe method overload that accepts a filter parameter. The filter parameter is of type System.Predicate<TPayload> and is executed when the event is published. If the filter predicate returns true the subscriber callback is executed.

public WarehouseUserControlViewModel(IEventAggregator eventAggregator)
{
    _eventAggregator = eventAggregator;
    _eventAggregator.GetEvent<OrderPaidForEvent>().Subscribe(HandleOrderPaidForEvent);
    _eventAggregator.GetEvent<OrderPaidForEvent>().Subscribe(HandleOrderPaidForEventFiltered, ThreadOption.PublisherThread, false, IsStockLevelTooLow);
}
 
private void HandleOrderPaidForEventFiltered(object payload)
{
    ShowWarning = true;
}
 
private bool IsStockLevelTooLow(object payload)
{
    return (_itemsInStock <= 10);
}

The second subscription to the OrderPaidForEvent specifies a ThreadOption enumeration value, and a filter parameter. The ThreadOption.PublisherThread enumeration value specifies that the event should be received on the publisher’s thread. The filter parameter specifies that the IsStockLevelTooLow predicate will be used to filter the event when it’s published.

The overall effect is that when the number of items in stock in the warehouse drops below ten, the HandleOrderPaidForEventFiltered subscriber callback is executed, which sets the ShowWarning property to true. This modifies the UI to display a warning to the user that stock levels are low.

Summary

In this blog post I’ve demonstrated how to use Prism for the Windows Runtime to perform event subscription filtering. This is achieved by using a Subscribe method overload that accepts a filter parameter. If the filter predicate returns true, the subscriber callback is executed.

The sample app can be downloaded here.

Monday, 5 August 2013

Event aggregation using Prism for the Windows Runtime

Previously I’ve blogged about how to perform validation using Prism for the Windows Runtime. In this blog post I’ll demonstrate how to use Prism for the Windows Runtime to perform event aggregation. Event aggregation allows communication between loosely coupled components in an app, removing the need for components to have a reference to each other. For more info about event aggregation see Communicating between loosely coupled components in AdventureWorks Shopper.

My hypothetical scenario for the accompanying sample app is a stock control system for an organisation that sells goods. When a user buys a good the number of items in stock in the warehouse decreases, whereas in the accounts department the number of items paid for increases. The sample app uses the Microsoft.Practices.Prism.PubSubEvents library, which is a PCL that implements event aggregation.

Implementation

In the sample app the lifetimes of event publishers and subscribers are independent because the objects are not connected by object references. There are also no type dependencies between publishers and subscribers – the publisher and subscriber classes can be packaged in unrelated assemblies.

The EventAggregator class is responsible for locating and building events. An instance of the EventAggregator class is created in the App class, and must be created on the UI thread in order for UI thread dispatching to work. The instance is then registered with the Unity dependency injection container so that it can be passed into view model classes through constructor injection.

private readonly IEventAggregator _eventAggregator = new EventAggregator();
 
protected override void OnInitialize(IActivatedEventArgs args)
{
    ...
    _container.RegisterInstance(_eventAggregator);
    ...
}
Defining the event

The PubSubEvent<TPayload> class connects event publishers and subscribers, and is the base class for an app’s specific events. TPayload is the type of the event’s payload, and is the argument that will be passed to subscribers when an event is publlished. The sample app defines the OrderPaidForEvent, which will be published whenever the user purchases an item.

public class OrderPaidForEvent : PubSubEvent<object>
{
}
This event is used to communicate between the loosely coupled MainPageViewModel, WarehouseUserControlViewModel and AccountsUserControlViewModel classes.
Publishing the event

When the user purchases an item the MainPageViewModel class calls the OrderPaidForEvent’s Publish method in order to publish the event.

private void PurchaseItem()
{
    _eventAggregator.GetEvent<OrderPaidForEvent>().Publish(null);
}

The EventAggregator’s GetEvent method constructs the event if it has not already been constructed, and publishing can occur from any thread.

Subscribing to the event

Loosely coupled classes can be notified when the OrderPaidForEvent is published by subscribing to it, using one of the PubSubEvent<TPayload> Subscribe method overloads.

public class WarehouseUserControlViewModel : ViewModel, IWarehouseUserControlViewModel
{
    private readonly IEventAggregator _eventAggregator;
    private int _itemsInStock = 437;
 
    public int ItemsInStock 
    { 
        get { return _itemsInStock; } 
        private set { SetProperty(ref _itemsInStock, value); }
    }
 
    public WarehouseUserControlViewModel(IEventAggregator eventAggregator)
    {
        _eventAggregator = eventAggregator;
        _eventAggregator.GetEvent<OrderPaidForEvent>().Subscribe(HandleOrderPaidForEvent);
    }
 
    private void HandleOrderPaidForEvent(object payload)
    {
        ItemsInStock--;
    }
}

Subscribers must provide an action with a signature that matches the payload of the event. For example, the HandleOrderPaidForEvent takes an object parameter. The method decrements that number of items that are in stock in the warehouse. This action will be executed by the subscriber when the event is published.

By default, the PubSubEvent<TPayload> class maintains a weak delegate reference to the subscriber’s registered action. This means that the reference that the PubSubEvent<TPayload> class holds onto will not prevent garbage collection of the subscriber. This approach relieves the subscriber from the need to unsubscribe from the event. The garbage collector will then dispose the subscriber instance when there are no references to it.

The overall effect is that when a user purchases an item the OrderPaidForEvent is published by the MainPageViewModel class. Both the WarehouseUserControlViewModel and AccountsUserControlViewModel subscribe to the event and respond to its publication by executing actions specific to each view model. All event publishing and subscribing occurs on the UI thread.

Summary

In this blog post I’ve demonstrated how to use Prism for the Windows Runtime to perform event aggregation between loosely coupled classes. When a publisher invokes the PubSubEvent<TPayload> class’s Publish method the system will run all actions that have been registered by the PubSubEvent<TPayload> class’s Subscribe method. Subscribers can control how the actions run. Subscriptions use weak references by default. Therefore registering a subscription action does not add a reference to the subscriber.

There’s a lot more to event aggregation than covered in this blog post. For more info see Communicating between loosely coupled components in AdventureWorks Shopper.

The sample app can be downloaded here.