Devlico.Us
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @devlicious

Casey Charlton - Insane World

Hang the code, and hang the rules. They're more like guidelines anyway

June 2008 - Posts

  • ADO .NET Entity Framework Vote of No Confidence

    Instead of repeating amongst us why the Entity Framework concerns us, an open letter has been written to hopefully persuade Microsoft to reconsider the Entity Framework, or at least some major aspects of it. To save me repeating it, here is what Dave Laribee said:

    A number of people have worked on an open letter to Microsoft and the
    Entity Framework team. It outlines the various deficiencies in the EF
    specifically related to concepts a lot of us value as solid working
    practice. Every effort has been made to balance honesty with diplomacy
    and cooperation.

    http://efvote.wufoo.com/forms/ado-net-entity-framework-vote-of-no-confidence/

    I'd encourage you all to sign if (and only if) this is something you
    agree with and please spread the word.

    Please read it carefully and understand where this is going ... if you agree - please sign it, and perhaps we can move Microsoft a little closer to some of the practices we feel are important.

     

  • Logging Without Using Castle Windsor and the Logging Facility

    As the discussion on the altdotnet list continued (some of it around my blog yesterday), it became apparent that some people didn't want to use an IoC container - but more confusing was that their objection to the whole pattern was that they thought the IoC container in here meant I was writing different code because I was using an IoC container. In fact nothing could be further from the truth - my service class would be identical in code, regardless of whether I used a container, or a factory, or any other construction on my object.

    Let us look at the proposed service class again, a little expanded from the last example to show a bit more detail:

        public class MyService : IMyService
    
        {
            private ILogger logger;
    
            public ILogger Logger
            {
                get
                {
                    if (logger == null) logger = NullLogger.Instance;
                    return logger;
                }
                set { logger = value; }
            }
    
    
            public void DoMyThing()
            {
                // Do something here
                Logger.Debug("Hello");
            }
        }
        public interface IMyService
        {
            void DoMyThing();
        }

    This service class is rather unimaginatively named, but has the basic parts in place. It has an optional ILogger property, and a method to DoMyThing(). One important thing to note is that the interface does not have an ILogger property.

    So if we don't use an IoC container, we need some way to create instance of this class. The "old fashioned" way would use the new keyword, but this leads to all sorts of maintenance problems later on, and so we prefer to use some other kind of construction pattern, in this case a Factory, so here is our "application", albeit rather simple:

       class Program
        {
            static void Main(string[] args)
            {
                IMyService service = MyServiceFactory.Create();
                // Note that IMyService does not have a Logger property ...
                service.DoMyThing();
            }
        }

    The thing to note here is that we only refer to the MyService class via the IMyService interface, so our consuming application does not know the service has a Logger property, nor does it care. In the Castle Windsor version earlier the line MyServiceFactory.Create() would have been something like IoC.Resolve<IMyService>() - but apart from that the consumer of the service has no idea how the object is being constructed, and nor does it care.

    For the sake of this example, here is some dummy code to represent our Logging classes. In the Castle Windsor case we use the ILogger in the Castle assemblies, we could also use that in this example, but would probably want to write our own if we didn't want to use any of the Castle code.

        public class log4netLogger : ILogger
        {
            public void Debug(string message)
            {
                // Send to log4net here
            }
        }
    
    
    
        public interface ILogger
        {
            void Debug(string message);
        }
    
        public class NullLogger
        {
            public static ILogger Instance;
        }

    Of course our ILogger will probably have a lot of other signatures defined, but this will do for now.

    So now the only part of the equation missing is the actual factory we are going to use to replace the IoC container.

        public static class MyServiceFactory
        {
            public static IMyService Create()
            {
                MyService service = new MyService();
                service.Logger = LoggingServiceFactory.Create();
                // Do other initialisation here
                return service;
            }
    
        }
    
        public static class LoggingServiceFactory
        {
            public static ILogger Create()
            {
                return new log4netLogger();
            }
        }

    That is all there is to it. It may seem like a lot of code to do a simple thing, and it is in a way - I would really try to avoid writing all this when Castle Windsor or an other IoC container will do all this for me - but it preserves one very important principle - the MyService class is totally clean, it does not have any knowledge of how it was constructed, and it does not know how it gets a logging class, it just knows that it can try and log something, and if it was meant to log, then it will.

    This is the principle of Seperation of Concerns at work - the class has only one concern, and it isn't how to create a logger object.

     

     

  • Logging with Castle Windsor, the Logging Facility and log4net

    A discussion on the altdotnet list just came up around logging. After some various suggestions, I asked what was wrong with using optional dependencies and the built in logging facility in Castle Windsor. It seemed the most obvious answer

    Of course, I completely forgot that when I first tried to figure this one out, it had me a little stumped and I took a while to find a good example of it. So here is how it happens.

    Optional Dependencies in Windsor

    When you ask the Windsor container for an instance of a class, it goes off and merrily tries to resolve all of the dependencies your class has. Firstly the constructor parameters, Windsor must find a constructor that it can provide all of the dependencies for - constructor parameters represent non-optional dependencies, they must be able to be fulfilled or Windsor will not give you an instance of the class back. You can have multiple constructors of course, and in this case Windsor will try and find the best match it can.

    This lead to one of the early suggestions on the thread, putting the instance of the Logger as a parameter on the class constructor. To me this is a horrible idea, logging, along with things like security and auditing are cross cutting concerns, the class really shouldn't have to care about them - their behaviour lives elsewhere.

    But Windsor has a really simple solution to this - optional dependencies. While Windsor must be able to fulfill at least one constructor signature, it will also try and resolve any public properties it can find on the class. These public properties may or may not be set by Windsor, if it has a suitable match for a property it will set it, otherwise it will ignore it.

    So the first part of the solution to the problem is to put a public property on the class with the logger interface - now Windsor will populate this property if it has a match in the container.

    The Logging Facility 

    Next is the magic bit, Castle already has simple integration for logging in the form of the Logging Facility.

    While you could just put your own class, that implemented your own logging, and passed this onto log4net, by using the Castle faciltiy you save a lot of messing around, and get a great deal of flexibility. The Castle facility supports:

    • log4net (requires Castle.Services.Logging.Log4netIntegration.dll)
    • NLog (requires Castle.Services.Logging.NLogIntegration.dll)
    • ConsoleLogger
    • DiagnosticsLogger
    • StreamLogger
    • WebLogger (TraceContext)
    • NullLogger (used as placeholder)

    Of course in the thread, log4net was the target of choice, but Castle lets you switch this simply, and maintain a single interface.

    How To Tie it Together

    1) Any class you are going to resolve from the Windsor container that you want to have logging on, add a public property of ILogger:

    public class MyClass
    {
       private ILogger logger;
    
       public ILogger Logger
       {
          get
          {
             if (logger == null) logger = NullLogger.Instance;
             return logger;
          }
          set { logger = value; }
       }
    }

    A key thing here is that we use the NullLogger as the default value - if the facility wasn't put into the container, or if the class was not instantiated via Windsor, then this will mean that logging just doesn't happen, rather than it creating an exception. The NullLogger just swallows the message and carries on. 

    2) Setup the Logging Facility in the Windsor container

    In the XML configuration:

    <?xml version="1.0" encoding="utf-8" ?> 
    <configuration>
    
    <facility 
        id="logging"
        type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging"
        loggingApi="null|console|diagnostics|web|nlog|log4net|custom"
        customLoggerFactory="type name that implements ILoggerFactory"
        configFile="optional config file location"    />
    
    </configuration>
    

    Or in the code intialization:

       container.AddFacility(
         "logging", 
         new LoggingFacility(LoggerImplementation.Console)); 

    3) Use the Logger instance from the class:

       Logger.Debug("Null shipment returned");

    That is all there is to it, any object that is resolved via Windsor will now be inspected for ILogger, and if found it will get an instance of the chosen logger. A simple solution, and a perfect example of why an IoC container can simplify your code.

     

  • The Language of Mocks (or is that Test Doubles)

    Ian Cooper brought up an interesting point on the altdotnet mailing list recently, around the language used to describe Mocks, or more accurately his preference for the term Test Double over my use of the generic term Mock.

    In most areas of development I can often be considered a language perfectionist, for example calling something a Unit Test when it is *clearly* an Integration Test drives me nuts - but when it comes to Mocks, Stubs, Fakes, Spys, or the rather more generic Test Doubles ... I just can't get passionate about the language.

    This all started a while ago, when people started using the term mock, but really it wasn't a mock - or more often they used the term mock when referring to what many mock frameworks call a Strict Mock, just one type of mock.

    Martin Fowler long ago posted on a clarification of the terminology around mocking, and xUnitPatterns has a fuller description. The distinction that Gerard Meszaros introduced was to use the term Test Double to describe all of these things we use to help us test our code. Fakes, Spys, Mocks, Dummys ... all just a type of Test Double.

    Now language is important. Very important. As Ian pointed out in his email, most arguments centre around a misunderstanding of the terminology involved - I'm sure the world would be a nicer place if language was universal and could not be interpreted differently by different people, but then it would be a linguistically poorer place for it too.

    In development, language is something that is vital to good communication of what are often very complex technical concepts. We evolved the languages of patterns and principles to allow us to avoid confusion and misunderstandings, and most areas of development have their own specific language terminology.

    But, with this one area of testing I have a problem with the terminology, because the term that I hear from developers on a daily basis is "mocking", not "test doubles". And when terminology enters the common language, it is very hard to replace it with a new term just because you prefer it. I'm sure that Test Double describes the concept better, and I'm sure that it is important to have some distinction between Mocks and Fakes, but in my experience, that is not how developers refer to these things.

    It is much easier to say "we can mock this out" than it is to say "we can create a test double here", the first is just more natural in the English language. So the term "mock" has become almost a defacto term for what Martin Fowler et al refer to as a Test Double, whilst also being a Mock with a capital M for describing the Mock that most mock frameworks create.

    So, much as I might like to be a language perfectionist on this one, I tend to just use the term mock, and leave the decision as to whether it is a Mock, Fake, Stub or Whatever to the point I actually code it. So far nobody has misconstrued Mock to mean "you must use a mocking framework", or at least not anyone to whom the concepts of mocking are not entirely new anyway, in which case much more clarification is needed in any case.

     

     

     

  • Superb Castle ActiveRecord Presentation from Hamilton and Oren

    Oren just posted a link to a presentation that he and Hamilton did at JAOO, explaining Castle ActiveRecord and giving some basic examples of its use within an application, and also touching on some trickier aspects of using an ORM.

    I cannot recommend this highly enough if you are interested in how an ORM can help your application, or how ActiveRecord can simplify NHibernate. Even if like me you have used ActiveRecord before I'm sure you will pick up some useful titbits from this presentation.

     

     

     

More Posts

Our Sponsors

Red-Gate!