Jun 15 2010

Law Of Instance Ownership

Category: Software Design | .NetRory Primrose @ 05:41

I’ve been writing a custom Unity extension for disposing build trees when a container is asked to tear down an instance. This has brought up some interesting ideas about the conditions in which an instance should be destroyed. This has lead to me come up with the Law of Instance Ownership.

Law of Instance Ownership

An instance is owned by the highest stack frame that holds a direct reference to an instance, or the application domain for globally held instances.

A common misconception is that the member that creates an instance is responsible for its lifetime management. The scenario that quickly breaks this idea is when a member returns an instance that requires lifetime management (such as IDisposable instance). In this case, the method that created the instance can’t destroy it because its usage is outside the scope of the member that created it.

Take System.IO.File.Open() method for example.

public static FileStream Open(string path, FileMode mode, FileAccess access, FileShare share)
{
    return new FileStream(path, mode, access, share);
}

This method returns a Stream which must be disposed when it is no longer required. While the File.Open method created the stream instance, it is up to the member that owns the stream to dispose of it.

What about instances that require lifetime management that are stored as fields on a type?

The impact here is that the class that defines the field (the owning class) will itself require lifetime management. For disposable types this will mean that the owning class will need to implement IDisposable. The lifetime management of the owning class is then the responsibility of the member that holds an instance of it. When that member disposes the owning class, the owning class will in turn dispose of its field instance.

This law should be used to determine who is responsible for lifetime management of an object instance. Only the owner of the instance should be responsible for handling this lifetime management.

Tags:

Feb 17 2010

Recommended reading for developers

I was reminded this morning of an email that I sent to the junior developers on my team when they joined us. It is an overview of some of the development practices, patterns and products that they would get exposed to on our project. I have included it here as a reference collection for others.

Principles and Patterns

These are things that I often use and are still learning to use.

Jeremy Miller also writes a series called Patterns in Practice for MSDN Magazine (see list at http://msdn.microsoft.com/en-au/magazine/cc720886.aspx). They are all a good read, especially:

Tools

These are tools that are good to get experience using. Most of them relate to the patterns above. There are other tools used like ReSharper, dotTrace, StyleCop, WinMerge etc, but they don’t have the up skill requirement that the following tools do.

Probably the most important tool to start using is Rhino Mocks. The only way to get experience with it is to start writing unit tests in VS. See the documentation at http://ayende.com/wiki/Rhino+Mocks+Documentation.ashx.

Tags: , , , , , , , , , , , , , ,

Mar 11 2009

Lightning fast Australian broadband

Category: .Net | IT Related | Software DesignRory Primrose @ 19:45

I've been on ADSL2+ for a few years now. Having a possible maximum speed of 24Gb is nice, but the actual floats between 5-7Gb being 3.5km from the exchange. That's not great, but is fast enough for general net usage. Tonight however, surfing the net has been slow. Really really slow. So slow in fact, that www.speedtest.net tells me this.

In the test before this one, the upload speed was actually a tad faster than the download speed. Did someone say broadband???

Yep, I'm glad that broadband in this country is so fast. My sarcasm drips all the way from this post to this article. Broadband in this country is a disgrace which is a real shame.

Update:

This morning is better :)

Tags:

Nov 24 2008

Class vs Struct

Category: .Net | Software DesignRory Primrose @ 08:09

There is a lot of information around that discusses the differences between classes and structs. Unfortunately there isn't a lot of information available about when to use one over the other.

MSDN has a good resource which provides guidance on how to choose between classes and structs. It starts by describing the differences between the two and then provides the following advice.

Consider defining a structure instead of a class if instances of the type are small and commonly short-lived or are commonly embedded in other objects.

Do not define a structure unless the type has all of the following characteristics:

  • It logically represents a single value, similar to primitive types (integer, double, and so on).
  • It has an instance size smaller than 16 bytes.
  • It is immutable.
  • It will not have to be boxed frequently.

If one or more of these conditions are not met, create a reference type instead of a structure. Failure to adhere to this guideline can negatively impact performance.

The one that got me was having an instance size of 16 bytes or smaller. Several of the classes that I wanted to convert into structs defined string properties. Initially, I thought that a string would almost always be over 16 bytes making it inappropriate for a struct.

It later occurred to me that strings are reference types not value types. Any string variable is simply a pointer to the memory location that holds the data for that reference type. This means that the size of a string property in a struct is the size of IntPtr.

Structs are back on the menu.

Some useful links are:

Tags:

Oct 8 2008

WCF service contract design article

Category: .Net | Software DesignRory Primrose @ 18:26

I had a conversation yesterday regarding WCF service contract design with my tech lead at work. Funnily enough, I then got a comment on an old post that afternoon from Ciaran O'Neill which is really about the same topic. I thought that I should write up my thoughts on the subject. See here for the article.

Tags:

Oct 8 2008

Cache expiration policies article

Category: .Net | IT Related | Software DesignRory Primrose @ 08:11

I was asked recently about caching expiration policies in response to my rant in my Caching should not be the source of truth post and a comment I made in a post by Chris Blankenship. I have written an article about cache expiration policies which you can find here. It discusses the high level concepts in expiration polices and some suggestions about which options to pick. It makes references to HttpRuntime.Cache and the Caching Application Block in Enterprise Library.

Tags:

Oct 3 2008

IServiceLocator - A common IoC container / Service locator interface

Category: .Net | Software DesignRory Primrose @ 06:57

This is great news - My Technobabble : IServiceLocator a step toward IoC container / Service locator detente. This diverse group of people have been able to collaborate to create a common interface to use for IoC container / Service locator frameworks. Hopefully the adoption rate will be swift by the creators of the IoC frameworks. Congratulations guys, this is a great achievement.

It would be good to see the same outcome for a common logging interface.

Tags:

Sep 25 2008

Caching should not be the source of truth

Category: Software DesignRory Primrose @ 05:44

I just read the Two Reasons You're Not Using the Cache and How To Deal With Them article on Visual Studio Magazine. Overall, I like the intention of the article which is to promote caching, but I have some issues with some of the points made.

In the article, Peter addresses two of the common reasons that cause people to not use caching. These are data being stale and losing data. There is some good advice regarding stale data. People need to determine the volatility of their data to decide on cache expiration policies. There are also some notification services that can be used to flush the cache when data stores are updated.

The article then discusses issues about losing data. This is where I don't like the guidance provided. What I can't agree with in the article is the concept of having the cache as the source of truth of the application data. The article promotes the idea of keeping application data in the cache (usually in memory) when it is created or updated and only providing that information to the back-end data store when the item is removed from the cache.

The first thing that comes to mind is that if there is a power failure, you lose your data. He mentions two things about this. Firstly, he doesn't have a solution for this (there isn't one for this design as a power failure is a power failure). Secondly, if you have a power failure, you have bigger problems.

Well, the later might be true, but that doesn't mean you should use a design that destroys data just because you do have bigger problems like a power failure. In today's world, data has an incredibly high value and needs to be treated with more respect than that. As he discusses, web farms are also difficult in scenarios where the cache is the source of truth.

In my opinion, caching is there to assist performance. That is its only job. It shouldn't be used to hold on to data that doesn't exist in a back-end data store. Caching should be a view of data stored, not represent the data store itself (even temporarily). Appropriate expiration policies need to be applied to cache data according to business requirements and data volatility. Within the confines of those policies, if the cache has data, it should serve it. If it doesn't it can be populated with data from the back-end store until it is flushed according to the expiration policies for that data.

If this simple design of cache usage is implemented, there is no risk of losing data. It gives performance as a bonus as it is able.

Tags:

Aug 28 2008

Example of coding for testability

Category: .Net | Software DesignRory Primrose @ 07:40

I have done it again. In order to work on a particular project, I have been sidetracked into writing a utility to help me continue with what I am actually trying to do. In my defense, I did look around the net for an application that would do what I needed so I didn't have to write it, but no application seemed appropriate.

In essence, I need an application to resolve all the links internal to a website and check their status. This will give me an initial view of the state of the site. I then want to take all of those links and replay the analysis of those resolved links using a different base address. The reason I am doing this is because I am looking at migrating my Community Server based blog to use BlogEngine.Net instead. As part of that migration, I want to maintain as much of the Community Server url formats as possible so I don't lose my existing audience.

Given that this application is going to chew a lot of bandwidth (my entire site) along with the need for accurate results, I want to make sure that this utility is doing the right thing. Unit testing is critical for this to be successful. I quickly found however that my initial cut is not very testable.

Here is a simple example of how to take untestable code and make it testable. In the following examples, there is some logic in the ResourceResolver.GetResourceContents method that we want to test.

The untestable example

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
 
namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(String[] args)
        {
            ResourceResolver resolver = new ResourceResolver();
            Uri location = new Uri("http://localhost");
            String content = resolver.GetResourceContents(location);
 
            Debug.WriteLine(content);
        }
    }
 
    internal class ResourceResolver
    {
        public String GetResourceContents(Uri location)
        {
            HttpWebRequest request = HttpWebRequest.Create(location) as HttpWebRequest;
 
            request.Credentials = CredentialCache.DefaultCredentials;
 
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
 
            using (Stream contentStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(contentStream))
                {
                    String content = reader.ReadToEnd();
 
                    // Do something with this value 
 
 
                    return content;
                }
            }
        }
    }
}

This is untestable as a unit test. To write a test for this code will require an integration test as requests are being made to an external resource (http in this case). What if that resource is not available or produces unknown or unmanageable results? Unit testing normally requires more flexibility as the same code paths need different data thrown at them.

This code is a classic example. The HttpWebRequest class is not easily testable. Converting this code so that mocks and stubs can be used will allow unit tests to be supported.

The testable example

using System;
using System.Diagnostics;
using System.IO;
using System.Net;
 
namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(String[] args)
        {
            HttpResourceLoader loader = new HttpResourceLoader();
            ResourceResolver resolver = new ResourceResolver(loader);
            Uri location = new Uri("http://localhost");
            String resourceContent = resolver.GetResourceContents(location);
 
            Debug.WriteLine(resourceContent);
        }
    }
 
    public interface IResourceLoader
    {
        String GetResourceContents(Uri location);
    }
 
    public class HttpResourceLoader : IResourceLoader
    {
        public String GetResourceContents(Uri location)
        {
            HttpWebRequest request = WebRequest.Create(location) as HttpWebRequest;
 
            request.Credentials = CredentialCache.DefaultCredentials;
 
            HttpWebResponse response = request.GetResponse() as HttpWebResponse;
 
            using (Stream contentStream = response.GetResponseStream())
            {
                using (StreamReader reader = new StreamReader(contentStream))
                {
                    return reader.ReadToEnd();
                }
            }
        }
    }
 
    internal class ResourceResolver
    {
        public ResourceResolver(IResourceLoader loader)
        {
            Loader = loader;
        }
 
        public String GetResourceContents(Uri location)
        {
            String content = Loader.GetResourceContents(location);
 
            // Do something with this value
 
            return content;
        }
 
        private IResourceLoader Loader
        {
            get;
            set;
        }
    }
}

By abstracting an implementation that actually gets the resource contents (with a bit of Dependency Injection thrown in), we now have a ResourceResolver.GetResourceContents method that can be unit tested. The unit testing involved now needs to pass in either a stub or a mocked instance of IResourceLoader and we can safely test the logic of this method without requiring http requests.

When you develop code, please think about how it is going to be tested. Even better, write unit tests when you develop the code. You will quickly find out how flexible your code is for unit testing.

Tags: , , , , ,

Aug 11 2008

AOP in .NET

Category: IT Related | .Net | Software DesignRory Primrose @ 16:26

A few months ago I did some research into dependency injection frameworks. One of the interesting features provided by many of the Dependency Injection frameworks was the support for AOP. This is really interesting stuff and great for injecting logging and caching implementations without having to modify existing code.

There are several AOP implementations around (Oren Eini identified seven in this post) and I have always wondered how some of them worked. Unfortunately I never got the time to research it.

Using aspects in .NET - Part 1 is a post by Istvan that just popped up in my feed reader. He describes how to create an AOP implementation using ContextBoundObject and ProxyAttribute classes. I didn't previously know that combining these types in the .Net framework allows you to override the new statement. This is extremely powerful. I had assumed that this was the method that TypeMock used for creating unit testing mocks, but Oren's post identifies it as using a profiling API.

I think the centerpiece of Istvan's implementation is the RealProxy class. This is another one of those .Net classes that is incredibly powerful. I have used RealProxy before to create a wrapper for WCF channel management. Thankfully this helped me to understand Istvan's post quickly. I am looking forward to his Part 2 post.

The only thing I don't like about this style of AOP is that it requires the aspected class to derive from ContextBoundObject and have a ProxyAttribute derived attribute decorated on the class. This has the disadvantage that the aspected class must be not only designed for AOP, but coded for this specific type of AOP. I'm a fan of POCO code design, so at this stage I think the profiling API version of AOP used by TypeMock is so much more powerful and has less impact on the code.

BTW, Castle Windsor was my pick of the dependency injection frameworks as it was the most suitable for my requirements. I also did some research into mocking frameworks about the same time. While TypeMock was certainly the most powerful, its particular implementation isn't very flexible. Oren's RhinoMocks was my pick on that one.

Tags: , ,