Archives

Archives / 2008 / February
  • Thinking Inside the Box and Premature Optimization

    At the last DC ALT.NET meeting, there was a good discussion regarding premature optimization.  Anything that involves this brings me to a rather famous quote by a great computer scientist, Donald Knuth which states:

    "We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil."

    Don't Think Five Steps Ahead
     
    The context of the conversation revolved around how when you learn a new language, you have a tendency to think inside the box and try not to prematurely optimize the code, instead, just meet the original intent of what you were trying to do as quickly and efficiently as possible and make it conform to the specification.  For example, one person there was a .NET guy who knew nothing of Java until put on a project recently where it was exclusively used.  This forced him to think more clearly about the problem and not just throw design patterns, caching solutions and so on.  When we are familiar with a language and all of its nuances, it sometimes gets the better of us, and we start throwing frameworks in there that have done things for us in the past just because they seemed appropriate then. It rang very true for me as well when I did my first Ruby on Rails application and I saw that I didn't need to bring in X framework or Y framework and my solution did just fine without it.  In fact, I thought it was a stronger piece because I didn't clutter it with frameworks and instead solved the direct domain problem at hand first.

    It kind of reminds me of a conversation I once had with a developer which went like this:

    Me: Why did you use x for this piece?
    Him:  Because it's always worked for me in the past.
    Me:  What problem does it solve?  Did you have that problem this time around?
    Him:  Well, no, I was just thinking five steps ahead

    So, basically what we can infer from this conversation is that the pain point just hadn't been hit yet.  Instead, reflexively, we have a tendency to throw these things in there because at one point, for one particular project, we felt that pain.  That's not to say that optimization is a bad thing, but once we start doing it, we need concrete measures for what the optimization is trying to fix and how well it does it.  Another part to consider is how easy is it to read.

    ADD with DDD

    Some of the guidance for this can be traced back to Domain Driven Design.  With this, you pay more attention to the model, the ubiquitous language and so on, and the frameworks in turn will come into play.  Instead, many people put their frameworks first and try to get the domain model to fit around it.  They are distracted by shiny things with their ADD to put the domain model first and then the frameworks.  I know I've been guilty of it in the past and it's been a learning adventure when I was earlier in my career.

    I'll be back next with a real technology post on IoC, Unity and all that, so stay tuned.  Until next time...

    kick it on DotNetKicks.com

  • Adventures in F# - F# 101 Part 2

    Update:  Added more topics

    I know it's been a little bit too long since I began this series from when I continued, but plenty of distractions came up along the way.  I intend to go a little deeper today into what functional programming means and why you should care.  As always, check out my previous post on the matter here.

    Getting Sidetracked

    Last night at the DC ALT.NET meeting, Craig Andera and I discussed Lisp, F# and functional programming as a whole.  His language of the year was Lisp and I thought that was an interesting choice of the language to learn, but when you think about it, most good things in programming lead back to SmallTalk and Lisp...  I had been hearing a bit about IronScheme, the IronLisp rewrite,  so of course I had to check it out.  Maybe this will be one of my future languages to learn, but I had enough exposure during my college years to last a little bit, so it's on the plan anyways.

    Basic Introduction

    So, just in case you missed the idea of functional programming and what it means, I have a few posts on where you should start here:
    But, if you really want the condensed version, Bart de Smet has a really nice introduction on functional programming in a series, although incomplete, which you can read here:
    Now that I take it you have read that and caught up, let's continue onto today's part.

    The Joys of Currying

    Where we left off last time was just dealing with the basics of functions and the fact that they are treated as values much like any other "variable".  Now let's get into a popular topic among functional programming, a concept called Currying.  The term was invented back in the earlier days of functional programming after the early logician Haskell Curry.  He's so good in fact that he got not only a functional programming style named after him, but a language named after him with Haskell.  If you listen to the DotNetRocks Episode 310 with Simon Peyton-Jones, you can learn more about that.

    Anyhow, the basic idea of Currying is to take a function with multiple arguments and transform it into a function that passes in only one argument, with the other arguments specified in the Currying function itself.  So you can think of it as a function that calls another function and returns a function.  You can think of it also as being a partial function.  So, let's actually get down to it and write some F# code to show how to do this:

    #light

    let n = 10

    let multiply a b = a * b

    let multiplyByFive = multiply 5

    let result = multiplyByFive 4

    printfn "result = %i" result

    So, what I accomplished above is that I had a function called multiply that takes two arguments, a and b.  Then I created a currying function called multiplyByFive which curries the multiply function by supplying a five value.  Then I can call the multiplyByFive curried function with a 4 and sure enough the result is 20.

    As always, I'm always curious on how it looks through .NET Reflector to see how F# does its magic.  So, let's crack that open and take a look.  First let's look at the tree of Reflector to see what it creates for us:



    Now as you can see, it created the multiply function.  Then we also have a multiplyByFive FastFunc function.  The functions get stored in the namespace free area and yet the main function gets placed elsewhere.  Now, let's look at the function implementation itself.



    From what you can see, it created a SampleFile class because I created a SampleFile.fs to create the curried functions.

    For those of you who are C# buffs, well, you can also do the same in C# with the new anonymous function type, System.Func in .NET 3.5.  Mads Torgersen, the C# Program Manager, noted on his blog quite a while ago asking the question, "Is C# Becoming a Functional Language?".  This post was pretty great and it's unfortunate that he doesn't blog as much as he does.  Remember kids, this isn't as pretty as F# because it's not what C# is really good at, but slowly but surely, functional programming paradigms are slowly seeping into C#.

    namespace CSharpCurriedFunctions
    {
        public static class CurriedFunctionExtensions
        {
            public static Func<A, Func<B, R>> Curry<A, B, R>(this Func<A, B, R> f)
            {
                return a => b => f(a, b);
            }

        }

        class Program
        {
            static void Main(string[] args)
            {
                Func<int, int, int> multiply = (a, b)=> a* b;
                Func<int, Func<int, int>> curriedMultiply = multiply.Curry();
                Func<int, int> multiplyByFive = curriedMultiply(5);
               
                Console.WriteLine("result = {0}", multiplyByFive(4));
            }
        }
    }

    If you're interested more in doing this with C#, I would suggest you head over to Dustin Campbell's blog and read the post about The Art of Currying.  For those who want to learn more, well, Dustin should be at ALT.NET Open Spaces, Seattle and hopefully will submit an F# topic for us to get our heads around. 

    How useful is this in C#?  Well, time will tell, but you could imagine having some search criteria for your repository using curried functions to "overload" with values.  Anything is really possible, but as you can see, it's a lot cleaner in F# and that's where it really shines.

    The Odd Tuple

    When specifying arguments to any given function, you can specify them without parentheses much as you would in VB.NET should it be a subroutine.  This is really helpful if you want to enable currying and such.  But, you can also specify them as a tuple.  For the math illiterate among you, that simply means a sequence of objects of a specified type.  This you must put within parentheses.  This makes you supply all arguments at once.  A simple example of this would look like this:

    #light

    let add (a, b) = a + b

    let result = add(3, 4)

    printfn "result = %i" result

    Pretty simple example and of course the result would be 7.

    Where is the Returns Department?

    As you may have noticed from the functions from above, I never really did specify any return type or return statement.  Implicitly behind the scenes, F# does that for you.  Basically when you define a function, you should indent with a tab and the last assignment becomes your return value.  The return is implicit right after the indenting is ended.  So, let's take a simplistic view of this:

    #light

    let addThings a b  =
      let c = a + b
      sprintf "result = %i" c

    let result = addThings 3 7

    print_string result

    As you may notice, when using the light syntax (#light), you cannot indent, instead just use two spaces and that should suffice.  Anyhow, you may note, I was doing a simple addition and then my final assignment becomes my return value, which is using the sprintf function, which to you C buffs out there, should look familiar.

    Conclusion

    I've got a lot more on this topic quite frankly and still just covering the basics of your first F# program.  There is so much to learn on this, but these are the basic building blocks you need to make that leap into functional programming.  It's becoming more interesting year by year as our languages such as Ruby, C# and so on continue to drive towards functional programming, so it's important to grok the fundamentals.  Next time, I hope to cover some recursion stuff, functions, lists and even operators (the really fun stuff).  Until next time...

    kick it on DotNetKicks.com

  • DC ALT.NET Wrapup and CI Factory

    Well, due to the weather beyond our control, the crowd was a bit smaller than expected at the February meeting of DC ALT.NET.  It seems people panic in the Washington DC area if there is even a hint of moisture in the air or a snow flake hits the ground.  It was a smaller crowd, yet passionate and I'd rather have that then a big crowd that wasn't involved at all.  We had such people as Craig Andera, Jay Flowers, Kevin Hegg among others who attended.  But the topics were great talking about functional programming, with Craig and Lisp and me with F#, continuous integration, the complexity of .NET and what's coming down the line, Domain Driven Design and managing complexity in projects.  Not once did a laptop nor PowerPoint show its head, instead just passionate people talking about technology and ways of thinking.

    I want to thank the people at Stelligent and Jay Flowers for making this happen.  It couldn't have been better timing as he just released version 1.0.1 of CI Factory yesterday.  If you aren't aware of this product, I've blogged about it in the past here.  What it does is it creates an out of the box CI environment which is really important to have in an agile environment.  Even teams as small as one person can benefit greatly from continuous integration.

    Tools supported by CI Factory include:

    Jay and Scott Hanselman did an episode on DNRTV about CI Factory here.  Of course Scott was being a little snarky for Jay's spelling, but oh well.  So, go ahead and give it a try.  I've found it very useful and pretty easy to use even for some of the smaller side projects I've done.

    kick it on DotNetKicks.com

  • Lang.NET Videos Now Available

    As you may have seen from previous posts, I have been covering Lang.NET and some of the interesting things that came from it.  I've always been interested in compilers, DSLs and such, and I hope you found them interesting as well.  I covered it these posts here:

    Anyhow, they have finally posted the videos from Lang.NET and are now available here for your review.  They have the talks from Anders Hejlberg for C#, Luke Hoban from F#, John Lam for IronRuby, Roman Ivantsov for Irony, Tomas Petricek for Phalanger and F# and so on.  Go and check them out.  Pretty cool stuff!

    kick it on DotNetKicks.com

  • Final Reminder - DC ALT.NET Meeting 2/20 - 7PM

    As posted previously here, the DC ALT.NET February meeting will be held tomorrow, Wednesday, February 20th, 2008 from 7-9PM.  Stelligent has been really kind to provide the facility and the food/drinks.

    Since we're following the Open Spaces Technology route, we don't have set speakers right now, but that may change over time.  We've been discussing some of the topics for the meeting:

    • Design By Contract (DBC) and Spec#
    • Aspect Oriented Programming and Castle Windsor
    • NHibernate Design Patterns and Implementation
    The details are as follows:

    Time and Location:
    Tuesday, February 20, 2008 7:00 PM

    Stelligent Incorporated
    Global Headquarters
    11495 Commerce Park Drive
    Reston, VA 20191

    So, bring your topic for discussion and bring your passion!

    kick it on DotNetKicks.com

  • IoC and the Unity Application Block

    Update:  Fixed code changed from CTP and More in the series:


    As many people who read this would know, I'm a big fan of IoC containers, more in particular Castle Windsor and StructureMap among my favorites.  Anyhow, lately, I've been playing with the Unity Application Block from Microsoft Patterns & Practices (P&P).  Very recently, Grigori Melnik, the product manager for EntLib 4.0 and the Unity Application Block announced the February 2008 Unity CTP.  Anyhow, it's been an active topic on the altdotnet list as well lately as noted here.

    Basic Overview

    If you're not familiar with the Unity Application Block, it was formerly the Dependency Injection Application Block.  The application block itself is built upon the next version of ObjectBuilder. For a good overview of ObjectBuilder, check out Chris Tavares's blog on the Deconstructing ObjectBuilder series:
    Back History

    I don't think it's any secret to anyone that many people hated the original implementation of ObjectBuilder.  I used it mostly in Composite Application Block (CAB) applications, but as well I've played with a few samples, enough to know it's too poorly documented to use in any type of system. 

    Below, I have a code sample of the original ObjectBuilder approach to build a singleton instance of a Logger object:
     
    Builder builder = new Builder();
    Locator locator = new Locator();

    // Create lifetime container for holding singletons
    ILifetimeContainer lifetimeContainer = new LifetimeContainer();
    locator.Add(typeof(ILifetimeContainer), lifetimeContainer);

    // Set my singleton policy for creating my logger
    builder.Policies.Set<ISingletonPolicy>(new SingletonPolicy(true), typeof(Logger), null);

    Logger logger = builder.BuildUp<Logger>(locator, null, null);

    It's not the most fun code to write, nor was it very well documented.  David Hayden, EntLib guru extraordinaire also had issues with it as noted here

    Another criticism lied in the fact that it was used in the EntLib, so it was hard for those to use another DI framework in its stead.  One of the big reasons behind ALT.NET was that the community wanted to help drive openness within Microsoft in terms of allowing third-party products to integrate fully within Microsoft products. 

    Since then the EntLib team announced that they would open up a bit, but also, they were revamping ObjectBuilder as well, and now packaging it under the Unity Application Block.  This of course was met with skepticism from such folks as Jeremy Miller (StructureMap), and Ayende (Windsor/Bindsor contributor).  Of course to say, Ayende's objection was around the duplication of effort seen with Microsoft and the Open Source Community.  See MSTest versus xUnit.NET versus MbUnit versus NUnit as an example of this.  Jeremy Miller saw this as at last some openness within the P&P team, and I'd have to agree that they are consulting the outside community, which is great to see.  It's great to see that P&P and others are actively involved with ALT.NET and the outreach efforts in the community.  Others are a bit concerned because of many shops won't consider the other products such as StructureMap, Spring.NET, Windsor because Microsoft has an offering instead even though the others may be a bit more feature complete.

    Taking it for a Test Spin

    So, now that I got that other stuff out of the way, let's take things for a quick test spin.  Let's walk through code how to do a basic setup using Dependency Injection with a constructor injection:

    namespace UnitySample
    {
        public interface ILogger
        {
            void Log(string value);
        }

        public class ConsoleLogger : ILogger
        {
            public void Log(string value)
            {
                Console.WriteLine(value);
            }
        }

        public interface ICustomerTasks
        {
            void SaveCustomer(Customer customer);
        }

        public class CustomerTasks : ICustomerTasks
        {
            private ILogger logger;

            public CustomerTasks(ILogger logger)
            {
                this.logger = logger;
            }

            public void SaveCustomer(Customer customer)
            {
                logger.Log("Customer Saved");
            }
        }

        public class Customer
        {
            public string FirstName { get; set; }

            public string AccountNumber { get; set; }
        }

        class Program
        {
            static void Main(string[] args)
            {
                IUnityContainer container = new UnityContainer()
                    .RegisterType<ILogger, ConsoleLogger>()
                    .RegisterType<ICustomerTasks, CustomerTasks>();

                ICustomerTasks tasks = container.Resolve<ICustomerTasks>();
                tasks.SaveCustomer(new Customer());
            }
        }

    And as you can see from this, on the console window, you should receive a "Customer Saved" message.  So, that's using constructor injection.  Instead, we could have easily done this through property setter injection which is another popular way of doing injection.  Let's rewrite it just a bit to do that:

    namespace UnitySample
    {
        public class NullLogger : ILogger
        {
            public void Log(string value)
            {
                // Do nothing
            }
        }
     
        public class CustomerTasks : ICustomerTasks
        {
            private ILogger logger = new NullLogger();

            public void SaveCustomer(Customer customer)
            {
                logger.Log("Customer Saved");
            }

            [Dependency]
            public ILogger Logger
            {
                get { return logger; }
                set { logger = value; }
            }
        }
    }

    And if using the same program.cs as above, it should work just the same.  These of course are really simple samples, but what most basic DI frameworks do.  This is pretty easy to set up so far in my adventures.  Now you could do like the other DI frameworks and be heavy on the XML configuration as well.  It's not hard to set this up either.  Below is a basic example of this XML configuration file:

    <?xml version="1.0" encoding="utf-8" ?>
    <configuration>
      <configSections>
        <section name="unity"
                 type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,
                       Microsoft.Practices.Unity.Configuration" />
      </configSections>
      <unity>
        <containers>
          <container>
            <types>
              <type type="UnitySample.ILogger,UnitySample"
                    mapTo="UnitySample.ConsoleLogger,UnitySample" />
              <type type="UnitySample.ICustomerTasks,UnitySample"
                    mapTo="UnitySample.CustomerTasks,UnitySample" />
            </types>
          </container>
        </containers>
      </unity>
    </configuration>

    Now that we got the XML config done, let's then reimplement our program.cs to handle this:

    namespace UnitySample
    {
        class Program
        {
            static void Main(string[] args)
            {
                IUnityContainer container = new UnityContainer();

                // Load from config file
                UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                section.Containers.Default.GetConfigCommand().Configure(container);

                ICustomerTasks tasks = container.Resolve<ICustomerTasks>();
                tasks.SaveCustomer(new Customer());
            }
    }


    Wrapping it Up

    So, as you can see, it's pretty easy to get started.  This of course is the 1000 ft overview of what it can do.  Competition is a good thing when it comes to creating these frameworks.  Choice is a wonderful thing...  I am especially encouraged by P&P's openness to the community, as well as some in the community to give back and give feedback to Microsoft for these frameworks.  Without one, the other cannot become stronger.  I'm encouraged from the early signs of Unity and I've enjoyed the samples and playing with it as much as I have.  Give it a try and better yet, give feedback to the team...

    Until next time...

    kick it on DotNetKicks.com

  • ALT.NET Seattle Registration and Mispronouncing My Last Name

    Just a reminder that ALT.NET Open Spaces, Seattle registration is still open, although we are sold out at the moment, we are taking stand-by's just in case some drop out.  So, if you hadn't registered with us, go ahead and do so, and don't let the sold out scare you.  Just keep in mind that you may not be selected, so I wouldn't make concrete plans if you are traveling to get there.

    I'm hoping to finish up about 5-6 posts that have been sitting around since last week on F#, the Unity Application Block, Mocking versus Stubbing and so on.  Hopefully today I'll get some of that done, so stay tuned.  That and there is a DC ALT.NET meeting this Wednesday as well.

    So, I know this is a random post, but if you caught over the weekend, the "This Week on Channel 9: Feb 15 with Scott Hanselman!" episode on Channel9, you may have noticed I was mentioned around minute 11, and it was a struggle to Brian Keller on how to pronounce my last name.  Don't worry about it, people, it happens all the time, and I usually let people struggle with the first part for a while before I have to hop in.  It's a definite way of telling who knows me and who doesn't...  It's like "Podwa Podwe Probably not gonna work here anymore, that's for sure!" from Office Space.

    kick it on DotNetKicks.com

  • Resharper 4.0 Nightly Builds Now Released

    A recent announcement was made on the altdotnet mailing list that made me jump for joy today.  Ilya Ryzhenkov and the great folks at JetBrains have published the nightly builds for Resharper 4.0.  The download for this can be found here and you might want to read the release notes here.  It's important to note that the LINQ syntax is still not supported yet.  As with any product in nightly builds, please use with caution, but download it and play with it today!

    kick it on DotNetKicks.com

  • RockNUG Meeting - ASP.NET MVC + Updates

    Tonight, put on the DVR and come out to the Rockville .NET Users Group (RockNUG) for a presentation by Jeff Schoolcraft on ASP.NET MVC

    The timing of course couldn't be more appropriate as ScottGu has recently posted about the ASP.NET MVC Framework Update in which he talks about a few pain points I know I've been having as well as others such as:

    • Can be deployed in partial trust in the \bin directory
    • Improved routing features and infrastructure
    • Test wizard now supports and probably one of my favorite features
      • MSTest
      • NUnit
      • MbUnit
      • XUnit.NET
    • Removing ControllerAction Attribute requirement from controllers, instead all public members will be controller actions.  Another nice thing to remove a pain point
    • Filter Support for Controllers and Action methods
    • HTML Helpers now built in
    • And so on...
    The plan is to release a new preview at MIX08, so it should be pretty exciting to get the hands on the new bits.

    Phil Haack has also covered this with his comments on ASP.NET MVC Update and Blocking Direct Access to Views in ASP.NET MVC.

    Anyhow, back to the original intent of the post, the details are as follows:

    An Introduction to ASP.NET MVC
    presented by Jeff Schoolcraft

    Come walk with me as I lead you on a gentle, relaxed tour of the ASP.NET MVC Framework. I'll demystify the forest of three letter acronyms. Then we'll take a journey through the hall of ancestors--and cousins--to discuss some influences and other players in the MVC space. We'll end up at the Grove of Hello World and, like habitat for softwarity, we'll build a demo application. Along the way we might run into some tangential trolls, but we'll cross that bridge when we come to it.

    Jeff Schoolcraft is the founder of The Queue, Incorporated; a consulting shop that writes software and helps write software better. He has been in the .NET space from nearly the beginning and is still, mostly, writing web applications in C#. He tries to organize a couple Code Camps a year and is hoping to find a developer community that isn't over an hour away. When he's not immersed in code he enjoys spending time with his wife and two daughters.

    Time:
    Wednesday, February 13, 2007 6:30-9:00 PM

    Location:
    Montgomery College, Rockville
    Humanities Building - Room 103
    Rockville, MD
    Click here for details....

    Come and support the organization if you're in the area!  Should be a great session!

    kick it on DotNetKicks.com

  • ALT.NET Open Spaces, Seattle Sold Out!

    Within a mere set of hours, ALT.NET Open Spaces, Seattle is officially sold out!  Don't worry if you have a registration code, you still have plenty of time to register.  We have a wait list if you still wish to attend, so don't let that discourage you at this point.    We had a great reaction and I'm really excited to see such a great turnout.  As you can notice from our participants page, and it will be growing of the people with registration codes, but we have such people as Jim Shore, Open Source folks, community folks (too many to mention, and if I missed your name I apologize) and Microsoft folks such as Scott Guthrie, Scott Hanselman, Brad Abrams, Phil Haack, and Chris Sells.  Stay tuned for future updates to all those who registered.  Going to be a great time!

    kick it on DotNetKicks.com

  • ALT.NET Open Spaces, Seattle Registration Open

    Darn it, Dave beat me to it here

    Anyhow, yes, as noted, the registration for ALT.NET Open Spaces, Seattle is now open and you can find it here.  This site requires OpenID in order to register with just your name and email address.  Feel free to use any of these OpenID servers on the OpenID Servers PageMyOpenID or Versign's PIP both worked for me, so you should have no problem.

    We have already 50 pre-invites, so that makes about 100 for general registration right now.  It's going to be a great crowd and a lot of big names.  We've been working very hard on this effort and it's going to be a great time with lots of events and great topics to discuss.

    The hotel logistics have been worked out and information can be found on the site.  So, check it out, and register today, and be there!

    kick it on DotNetKicks.com

  • Adventures in F# - F# 101 Part 1

    Update:  Added more topics

    In some previous posts, I pointed you to a bunch of links to help get me started.  I'm still working on some more thorough examples, but this time around I'm going to walk you through the F# 101 much like I did with Spec#.  What we first need to understand is the key differences between imperative and functional programming. 

    I've really enjoyed Robert Pickering's book Foundations of F# and Don Syme's Expert F# book as they both give a good overview of not only the language, but the uses.  It's a lot for some stuck in the imperative world to think about functional programming, but these books do their job well.

    So, today I'd like to cover the following topics:
    • Hello World Sample
    • #light
    • Functions == Values basics
    Hello World Example

    As I like to do with most languages, I know it sounds trite, but Hello World, especially in .NET languages is interesting, especially how they translate in IL through Reflector.  F# is especially interesting in this case as it is a functional language built on top of a imperative framework such as the CLI and C#. 

    So, let's walk through a simple example.  First, of course you need to have F# installed which can be found here.  Then go ahead and create a new F# project, which should be under the Other Project types.  By default, it will not give you any classes as part of your project.  So, go ahead and add an F# Source File.  It will give you the extension of .fs by default.  I went ahead and created a class called HelloWorld.fs.  Get rid of the default text that is in there, and it is plenty, and just put in the following code:

    #light

    print_endline "Hello World"

    As you can see from the simple example above, we've put in the #light directive.  I'll cover what that means shortly.  But anyways as you can notice it calls a default global function called print_endline.  I always like to look at what the code compiles to in Reflector to IL, so let's take a look at that.



    What's really interesting to see from the above, by default, it created the main function for us without us explicitly doing so.  Also, it notes that we are calling an OCaml function.  If you look through Reflector and the FSharp.Compatibility.dll, you'll notice it takes a few things from OCaml as its base.

    Where to Turn

    As always, if you have problems, the specification and the books help out well with this.  If you should get lost, the information F# specification is very good at defining the language and can be found here.

    Stay in the #light


    From the above example and many other examples you will see from me, you'll notice the #light directive at the top of every source file.  What this does is that it makes all whitespace significant.  This directive allows you to omit such things as begin, end, in and the semi-colon.  When defining functions and so on, you indent your code to make it fall under that scope implicitly by using that directive.

    Identifiers, Keywords and Literals

    In F#, it's important to realize that variables, aren't really variables, more like identifiers.  In pure functional programming, it's fundamental to understand that once a "variable" is assigned, it is immutable.  However, if using F# an imperative way of thinking, then it can be.

    To make a simple assignment, just use the simple let keyword such as this:

    #light

    let message =  "Hello World"
    printfn "%s" message

    One of these identifiers can be either either just a simple value, or even a function, since these functions are values as well.  I'll cover that more shortly in the next section. 
    #light

    let rec fib n = if n < 2 then 1 else fib (n-2) + fib(n-1)
    printfn "%i" (fib 10)

    I think this example went a little too far with adding recursion, but you get the point that it's pretty easy to define a function much as you would with any old "variable".  Also, you may note, I'm not returning anything from this function, but in fact I am returning the Fibonacci sequence that I asked for.

    If you also note the keywords, there are a lot of direct mappings from C# to F#, but it's also interesting that it has a list of reserved keywords for future use such as mixin.  Now, if we finally brought mixins to .NET, well, then I'm all for it.

    Of the types that exist in F#, the only ones to note that are completely different are:
    • bigint - Microsoft.FSharp.Math.BigInt
    • bignum - Microsoft.FSharp.Math.BigNum
    It's interesting to know that the .NET framework's BigInteger class is internal, yet these are publicly available.  Both of these are rational large integers just in case you need that kind of thing.

    Functions == Values?

    Once again, like I said above, functions and values are one in the same in the pure functional programming stance.  You noticed that in my functions, I'm not returning anything, nor is it imperative that you do so explicitly.  This boggles many of OO mindsets, I'm sure and there are a lot of things in FP that an OO person may have problems with.

    Let's walk through another simple function, but this time, we'll implement that main function and look at the results through Reflector.

    #light

    let rec fib n = if n < 2 then 1 else fib (n-2) + fib(n-1)
    let print x = printfn "%i" x

    let x1 = fib(10)
    let x2 = fib(20)

    let main() =
      print x1;
      print x2

    main()

    From the above sample, I created two functions, a recursive Fibonacci sequence function from above, and I also created a print function which calls the native printfn function which is a variation of the printf function with a newline at the end.  For those who are curious about what it looks like in Reflector, let's take a look, and this time in C#.  Instead of pasting a bunch of screenshots, it's much easier to paste it below the pieces we're interested in.

    fib function:
    public static int fib(int n)
    {
        if (n < 2)
        {
            return 1;
        }
        return (fib(n - 2) + fib(n - 1));
    }

    print function:
    public static void print(int x)
    {
        Pervasives.printfn<FastFunc<int, Unit>>(new Format<FastFunc<int, Unit>, TextWriter, Unit, Unit>("%i")).Invoke(x);
    }

    main function:
    public static void main()
    {
        print(get_x1());
        print(get_x2());
    }

    So, as you can see, it's doing much like we think it would be, as it fit everything into our HelloWorld class.  The more interesting pieces are how C# and F# functions differ.  It's just interesting to see how FP fits on top of an imperative programming framework.

    Next time, I'll cover more with functions such as Currying, Tuples, Recursion, Scopes and so on.  Plus I need to talk about the interop story here which is strong between F# and C# as well.  There's a lot to cover and quite frankly, it's making me stronger as well to go over this time and time again.

    Conclusion

    This is the first post in the series.  As you can see, I have plenty to cover in the next installment.  If you like the series and so on, subscribe and keep coming back.  Until next time...

    kick it on DotNetKicks.com

  • Adventures in Compilers - Building on the DLR

    So, I can admit, I've been on a bit of a kick with compilers and such after my posts on DSLs, Compilers and the Irony of it All and Lang.NET and Rolling Your Own.  Today is no different, but this time, I'm just intrigued by targeting the DLR instead of the CLR.   Thankfully there are a few great references that people are doing right now for these little adventures.  One day once I'm more finished with the deep dive into F#, I'll dig a little deeper.

    So, to get started, head on over to the IronPython download at CodePlex and let's get started.  The DLR doesn't compile down to MSIL, instead expression trees.  The DLR contains a set of expression trees that allow you to define variable assignments, functions, loops, if/then/else, and much more.  After making the DLR expression tree from the aforementioned pieces, the DLR handles the code.  This will be covered by Martin Maly in some of his posts.

    Building Your Own DLR Language Series

    Martin Maly from the Microsoft DLR team has started a series on building languages on top of the DLR.  The posts in the series are so far:

    • Building a DLR Language - ToyScript
      This post covers the basics of the ToyScript sample from the IronPython download.  This covers the tokenizer, parser and the Abstract Syntax Tree (AST).  This is the starter for the series.

    • Building a DLR Language - Trees
      This post covers that the ToyScript language generates not MSIL, but instead trees which the DLR then take care of the code generation.  This also covers the expressions that the DLR trees support

    • Building a DLR Language - Trees 2
      This is a follow-up to the previous post and covers the constructs for creating functions and lambdas. 

    • Building a DLR Language - Dynamic Behaviors
      This post covers dynamic behaviors, instead of the previous samples which covered static linked and strongly typed.  This sample covers arbitrarily adding two objects.

    • Building a DLR Language - Dynamic Behaviors 2
      This is a follow-up to the previous post on dynamic behaviors, and this time covers using the ActionExpression.  This time he digs into Reflector to show samples of the output.  Very cool stuff...

    • Building a DLR Language - Dynamic Behaviors 3
      In the final post so far in the series, it covers what happens when the DLR encounters a new runtime condition it hasn't seen and doesn't know yet how to handle.  These conditions are handled by Rules in the DLR sense.
    Building on the DLR

    Tomas Restrepo recently blogged about just that kind of adventure as well with some good posts recently.  Here are the ones so far:
    • Building On The DLR
      This is the first post in the series which gives an introduction to the basics and where to get started.

    • DLR Notes 1
      This post covers simple things such as declaring global and local functions and variables and the trials and tribulations.

    • DLR Notes 2
      This post is a rather long post about implementing function calls through Call Actions.  This includes such things as  call expressions,  IDynamicObject and ActionBinders

    • DLR Notes 3
      This is a follow-up which covers InvokeMember actions which are used to invoke instance members on .NET objects.
    Conclusion

    This is pretty exciting stuff as it has whetted my appetite for building dynamic languages.  My mind is still swimming with the possibilities of this, but to make one of these languages is simpler than ever.  Once again, I'll start taking that deep dive after I finish my F# kick, but I still thought I'd start gathering my resources now.

    Until next time...

    kick it on DotNetKicks.com

  • Software Transactional Memory and F#

    Since I have a rather long commute to and from work, I have the opportunity to get caught up on all sorts of podcasts and such.  Very recently, I listened to the DotNetRocks Episode 310 with Simon Peyton Jones on Haskell and Functional Programming.  It seems that Carl and Richard are definitely on a functional programming trip, and I think Scott Hanselman has joined the group as well with his shows on Hanselminutes.  Since I've been learning F# and such I thought this show was well worth a listen, and I was right.

    Simon Peyton Jones is currently working on a few things including the a Haskell compiler, Glasgow Haskell Compiler (GHC) and C--

    Haskell

    If you're not familiar with Haskell, it is a purely functional programming language, unlike F# which allows for imperative and functional programming in the same language.  The GHC is one of the more popular Haskell compilers out there today.  Much like every other language out there today, there are a couple, although inactive, Haskell .NET compilers out there including Hugs98 for .NET using the Hugs98 compiler, and Modrian using the GHC.

    Let's walk through a simple example of computing a factorial in one line:

    fac n = if n > 0 then n * fac (n-1) else 1

    As you can see from the above line, we create a function that keeps recursing itself until it hits 1. 

    Now, let's look at a simple version in the Hugs98 for .NET for a simple console application:

    main = do
      obj <- new "System.Object"
      x   <- obj # invoke "GetHashCode" ()
      print ("The hash code is: " ++ show (x::Int))

    Pretty slick actually...  Too bad they aren't being maintained anymore, especially with .NET 2.0 and beyond goodness.  But, if you're looking for more tutorials and such, go here for a brief demo from Simon himself.

    Software Transactional Memory (STM)

    One of the more interesting aspects of Simon's visit to DNR was talking about Software Transactional Memory (STM).  This has been one of Simon's projects at Microsoft Research and an interesting one at that.  STM originally came about back in the '80s, but only more practical now as many times it has failed in the past.  Think of STM being analogous to database transactions, but in shared memory for concurrent running programs.  The GHC has actually implemented this functionality and is pretty interesting.

    So, what does this offer us?  Well, with this scheme proposed in their paper, you can take two operations and combine them to be atomic.  In the past, it was unclear when and how they should attempt to re-execute the transaction should it fail.  So, in turn, Simon's group put in a retry keyword which uses a transaction log that determines the memory that was read and then automatically retries it and changes that piece of memory.  They also implemented the orElse keyword which brings an alternative in should the transaction fail the first time, then the alternative is run.

    You can read more about Simon's group's research paper here.

    STM in F#?

    So, this is really cool stuff, but can we have this in .NET?  Greg Neverov has indeed written a library called Software Transactional Memory for F# which is available on hubFS.  What's interesting is that the low level goo for the STM is actually written in C# using the Monitor class with method calls to Enter, Wait, Exit and PulseAll.  So, I guess you could call this library from C# as well to do concurrent programming, but that's more of F#'s gig.

    Here's a simple example using this:

    let enqueue queue item =
      stm { let! used = readTVar queue.used
            return! if used < queue.len
                    then stm { let! head = readTVar queue.head
                               do! writeTVar queue.a.[(head+used) % queue.len] item
                               return! writeTVar queue.used (used+1) }
                    else retry () }

    So, download it today and check it out.  There may be performance implications of using this code instead of just the standard Monitor.Enter and so on, but I've yet to check that out.

    Conclusion

    I barely scratched the surface once again on this and the possibilities.  You could easily imagine using this in heavy concurrent applications touching static data and shared memory.  A lot of these things give me the idea about the strength and power of F# and .NET languages as a whole.  .NET is rapidly evolving before our eyes and the possibilities of so many years ago with many languages using the same platform is really solidifying and each language has its purpose...

    Until next time...

    kick it on DotNetKicks.com

  • DC ALT.NET Site Now Up

    Well, after much trial and tribulation, we finally have our DC ALT.NET site up.  Thanks to Phil McMillan and Entropy Zero Consulting for hosting the site!  Right now it's a work in progress and I hope to have it more complete tomorrow.  As per usual with these kinds of groups, it's a wiki style and will be constantly changing with resources from our previous meeting, voting on the next topics at the next Open Spaces and places for sponsorship among other things.

    Meeting Announcement Redux

    Just a reminder about our third meeting of DC ALT.NET on February 20th at 7PM.

    The meeting this month will bring ALT.NET to Reston, Virginia and the Stelligent headquarters.  I want to thank Jay Flowers for offering his office as our get together.  The food and booze will be provided by Stelligent, so a big thanks to them!  Oh, and they are hiring if anyone is interesting (schilling off). 

    At our last meeting, CMAP hosted our event in which we discussed a lot of great topics.  You can read a wrapup of our last meeting here.  We're going to formalize things a little bit this time around and vote on topics for next time at this meeting so we can come prepared.  As a group, we're growing fast and learning a lot along the way.

    Looking for Sponsors

    As always, we're looking for sponsors for our events.  We bring a lot of passionate developers to your site and we feel we can bring a lot.  Sponsorship opportunities are always appreciated!

    Who We Are

    Are you a developer who always keeps an eye out for a better way? Do you look outside the mainstream to adopt the best practices of any development community, including Open Source, Agile, Java, and Ruby communities? Are you always looking for more elegant, more simple, more maintainable solutions? If so, then you might be an ALT.NET practitioner!
     
    This group follows the Open Space Technology model.  In Open Space, a facilitator explains the process and then participants are invited to co-create the agenda and host their own discussion groups.  So, we'll take a vote and present the topics.  We're in the pub-club mind occasionally, so it's not surprising to find us geeking out a bar...
     
    This model follows the four basic principles:

    • Whoever comes are the right people
    • Whatever happens is the only thing that could have
    • Whenever it starts is the right time
    • When it's over, it's over
    Topics

    Topics for discussion can include the following as well as others:
    • Model View Controller Pattern (ASP.NET MVC/MonoRail)
    • Inversion of Control (IoC) containers and Dependency Injection (Spring.NET/Castle Windsor/StructureMap)
    • Domain Driven Design
    • Design by Contract and Spec#
    • Continuous Integration
    • Agile
    Time and Location:
    Tuesday, February 20, 2008 7:00 PM

    Stelligent Incorporated
    Global Headquarters
    11495 Commerce Park Drive
    Reston, VA 20191

    Come, participate, and make your voice heard!  Come meet passionate developers like yourself in the active discussion.  Hoping for a great turnout...   If you haven't signed up for our list, go ahead and do that here.

    kick it on DotNetKicks.com

  • DSLs, Compilers and the Irony of it All

    In a previous post, I posted about the Lang.NET symposium and rolling your own compiler.  I cited an MSDN article that was a good starter for someone interested in writing that new language in .NET we've all been waiting for.  It's not by any means to get you towards finishing IronRuby by yourself, but some of the fundamentals are covered.

    The reason I've stated that I'm pretty interested is that of course I'm a geek, but I'm also interested in Domain Specific Languages (DSLs) lately as you may notice from my blog and what you can do with compilers to help that along.

    DSLs in General

    So, why DSLs and why am I interested?  I think Oren Eini, aka Ayende laid the reasons out well here and here.  In short he covers quite a few scenarios in which you might be interested in them, such as:

    • Mapping layers for DTO/Domain objects from incoming objects
    • Configuration scripting for IoC containers and so on
    • Business situations and Business Rule Engines
    And the list can go on.  In fact, he's actually writing a book about it, if you've been hiding under a rock somewhere...

    Ayende has been quite busy with the DSL posts that I encourage you to check out.  If you're looking for basic samples, check out these posts on Building an External DSL, and Implementing a DSL.  As you may note, most samples are written in Boo, but you could imagine them written in any language for that matter in the .NET space.

    Compiler Basics

    Now that we're through that section, let's take a step back to compilers in general.  If you're interested in these things, I would suggest the Compilers: Principles, Techniques, and Tools aka the Dragon Books.  Even though the first one was published back in 1977, there has been the Purple Edition released back in 2006.  There are several sample chapters available online if you wish.  This will give you a good foundation on how compilers work and give you more of a headstart than just the simple MSDN sample. 

    The Irony Of It All

    Greg Young pointed me towards Irony by Roman Ivantsov which is available off CodePlex.  If you paid attention to the Lang.NET 2008 symposium, Irony  and language challenges in ERP systems were covered as noted here.
     
    Off the site, it explains:

    Irony is a new-generation .NET compiler construction kit. It utilizes the full potential of c# 2.0 and .NET Framework to implement a completely new and streamlined technology of compiler construction.
    Unlike most existing yacc/lex-style solutions Irony does not employ any scanner or parser code generation from grammar specifications written in proprietary meta-language. In Irony the target language grammar is coded directly in c# using operator overloading to express grammar constructs. Irony's scanner and parser modules use the grammar encoded as c# class to control the parsing process.

    So, basically it takes the idea from that MSDN article and raises it to a whole new level.  And best of all, it's written in C#, so it opens compilers to a different audience instead.  For a full walkthrough of the possibilities, check out the article posted on CodeProject.  What's really cool is that he's opened it up for anyone to contribute to should you find something missing or not quite right.

    Greg brings out an idea of using Abstract Syntax Trees (ASTs) inside custom attributes to bring more of Spec# to the .NET framework.  He posted this simple sample of some of the possibilities:

    private void MyMethod( [Requires("value>5 and value<10")] int i) { ... }

    I think it's an interesting approach and I'm going to have to try it out.  I can't turn down a challenge like this.

    Conclusion

    So, as I continue on the journey of F#, DSLs and compilers, these things come to light and I find even after all these years, I'm still learning something new every day.  I hope you found this shallow dive into the deep end interesting into this geekdom.  Well, that and after going through some of these samples that my old lex/yacc skills aren't quite what they used to be.  With some time and perseverance, maybe it will...

    And yes, I'll be getting back to some code samples soon enough.  Until next time...

    kick it on DotNetKicks.com

  • Ruby.NET Is Dead; Long Live Ruby.NET

    As I noted yesterday, Dr. Wayne Kelly, the leader of Ruby.NET project, attended the 2008 Lang.NET Symposium last week led a discussion of how he wrapped Ruby, a dynamic language, on top of the static CLI.  Of note of course in that speech was how hard certain things are with Ruby due to the lack of a formal specification.

    Anyhow, fast forward to yesterday.  Wayne announced in a post yesterday about the future of Ruby.NET.  I encourage you to read the whole thing here.

    He writes:

    Ruby.NET started life in 2005 as an academic research project with the goals of learning more about the challenges of mapping a dynamic language such as Ruby onto the relatively static CLI platform. When we released our first beta in 2006, many people got excited and started blogging about the project, at which time the project took on a life of its own heading towards a production quality release that people could one day actually use. The release of IronRuby last year obviously caused us to question this unstated goal. At the time we didn't know if the IronRuby project and the DLR would succeed, so we decided to continue with Ruby.NET at that stage. Last week at the Lang.NET Symposium, I presented our work on the Ruby.NET project and also had the opportunity to learn more about the progress of the IronRuby project and the inner workings of the DLR (and also the JRuby project presented by Charles Nutter).

    I've come to the conclusion that the DLR is clearly here to stay - it's becoming an even more important part of the Microsoft platform. I also believe that to obtain production quality performance, Ruby.NET would need to reinvent (or adopt) something equivalent to the DLR. If we were starting the project today, there is no way we wouldn't use the DLR. Whilst Ruby.NET initially had a good head start on the IronRuby project; by incorporating the Ruby.NET parser and scanner and by leveraging the DLR, I now believe that IronRuby is more likely to succeed as a production quality implementation of Ruby on the .NET platform. I believe that ultimately there is no need for two different implementations of Ruby on .NET. So, if Ruby.NET is ultimately not going to be that implementation, then we should not waste further developer effort fruitlessly chasing that goal. There is still a massive amount `of work required to achieve full semantic compatibility, to achieve production quality performance and to get Rails to run robustly.

    There have already been a number of practical and research outcomes from the Ruby.NET project, however, at this stage, I believe we (the Ruby.NET community) can make the biggest impact by levering our experiences with Ruby.NET to contribute to the IronRuby and DLR projects. Personally, I still feel we have unfinished business - we set our selves the goal of running Rails on .NET and we haven't achieved that yet. If we can leverage our experience to help IronRuby get to that point, then I'd at least have the personal satisfaction of helping see the job completed.

    These are just my views. As a researcher, my prime interest is not in developing products, but in developing innovative new ideas and having an impact by having those ideas used in the real world. I'm aware that others in the community will have different goals and so will presumably have a different take on this - I'm keen to hear what you think. If anyone wants to press ahead, then the code base is still owned and controlled by you the community, so you are free to do with it as you please with our full blessing.

    I'd also like to make it very clear that this decision is entirely my own - based on research and technical considerations. Microsoft did not in any way suggest or encourage us to kill the project and we thank them again for their support of the project.

    I'd like to thank all of our contributors and supporters and apologize if this decision comes as a disappointment. I hope many of you will join me in contributing to the IronRuby project and see it through to a successful completion.

    Cheers, Wayne.

    So, what he's saying in other words is that it's best that he takes the lessons learned from the Ruby.NET implementation on the static typed CLI and contribute more towards IronRuby on top of the DLR instead.  I don't think that's going to dissuade anyone, and may preclude him, but I think others are willing and able to pick up the torch.  So far, my experience with the project had been good, although not as complete as I'd like.  But many of those problems come from the lack of a spec instead of anything squirrely done inside the code itself.

    John Lam has posted his reaction here on his blog.  The invitation is out to anyone to join and contribute to the IronRuby implementation.  So, all eyes turn towards the IronRuby team and anyone willing to step up to the plate...

    kick it on DotNetKicks.com

  • Lang.NET and Rolling Your Own

    Last week, the 2008 Lang.NET symposium was held last week.  If you're not familiar with what that is, it's a discussion about languages, compilers and libraries within the .NET space.  It's been one of those things I'd love to attend just to understand where Miguel de Icaza, Anders Hejlsberg, Luke Hoban, Jim Hugunin and others are going with their related languages.

    Lang.NET Stuff

    I followed Ted Neward's recaps as they were going on as to understand what all we were missing.  He was good enough to provide great writeups on the symposium and can be found here:

    So, there was a pretty wide array of speakers there including Tomas Petricek and his project Phalanger.  If you're unfamiliar with him, I've referenced him on several occasions when talking about F# as he's pretty deep into that as well.  Anyhow, he has assumed control of Phalanger which compiles PHP to IL and has recently added on Silverlight functionality as well.  What's really cool is that he's now working on Phalanger on the DLR.  His recap of the even can be found here.

    Ted Neward gave a presentation on Scala.  I don't think he sounded too pleased as to the way it went with ribbing from Don Box among others.  It'll be interesting to see how Scala progresses since it has been noted that Ruby is dead and Scala is in...   Scala on .NET is something that I have yet to fully explore but it's on the latter half of this year I think.  Right now it's a push on F# to get myself deep in that before anything else.

    Anders gave a talk as well as others.  It's going to be interesting to see the collision of functional programming into C#, taking ideas from F# and so on.  It's already happening with lambdas and the System.Func delegate type.

    F# was very well represented this year as Luke Hoban (F# Program Manager), Harry Pierson (Microsoft IT), and Tomas Petricek.  Harry has a good recap of what he saw here.  It's going to be interesting this year as F# becomes more of a first class player in the .NET space.  I'm loving F# in what I'm doing right now and all interested should put it on their learning list. 

    John Lam has a pretty good writeup as well with regards to Lang.Net as a whole here.  This time Ruby was well represented with Charlie Nutter, Wayne Kelly and John Lam.  John has a pretty good recap and slides of his talk and that can be found here

    Roll Your Own?

    So, why am I interested?  Well, compilers and languages is something I definitely geek about.  I've been looking at F# for creating my DSLs as well as looking at it to create compilers, both of which it can specialize quite nicely.  Robert Pickering's book "Foundations of F#" can start you on your way to that.

    With all this discussion about compilers, Joel Pobar published an article in the latest MSDN magazine called "Create a Language Compiler for the .NET Framework".   This is a pretty good starting point for those unfamiliar with creating compilers and unfamiliar with the lovely thing that is System.Reflection.Emit and how much of a friend it is.  I done a little bit of this years ago when I was creating a compiler for some DSLs that I created.  I realized that it was more trouble than it was worth, but still a worthwhile exercise.  But the point of the article is stating how easy it is to create or port a language to the .NET platform.  A very good read and the source code is pretty solid too.

    Until next time...

    kick it on DotNetKicks.com

  • Resharper 4.0 Early Access Program in Two Weeks?

    The good folks at JetBrains have recently announced that Resharper 4.0 Early Access Program will be available in two weeks.  It's like one of those long awaited things like Duke Nukem Forever, but it looks like R# will beat it to the punch, fortunately for me.  For those like me, I can honestly say I haven't been as productive in Visual Studio 2008 as I can say I have been without it.  Many people will use the workaround as stated many times around the blogs, but I've just stayed away until they can get it working just right.  Instead, I've been happy using it with Visual Studio 2005 in the mean time.

    The only thing now that keeps me with the Visual Studio 2005 sitting around continues to be BizTalk.  I imagine the next Service Pack of BizTalk 2006 R2 will contain the right templates, but it's frustrating that they haven't come out yet.  Either way, I can't wait until R# 4.0!  Until next time...

    kick it on DotNetKicks.com

  • Fluency in Fluent Interfaces

    Scott Hanselman's recent post about the Daily Source Code 14 - Fluent Interface Edition got me to think more on fluent interfaces and a previous post of mine on ObjectMother versus Test Data Builders.  Also, it comes to mind in regards to DSLs, both internal and external that has me intrigued.  Partially due to my latest involvement with Ruby and F#.

    Test Data Builder Example

    So, let's revisit that simple example:

    public class ClaimBuilder
    {
         private DateTime claimDate;
         private Provider provider = ProviderBuilder.StartRecording().Build();
         private Recipient recipient = RecipientBuilder.StartRecording().Build();
         private ClaimLineCollection claimLines = ClaimLinesBuilder.StartRecording.Build();

         public static ClaimBuilder StartRecording()
         {
              return new ClaimBuilder();
         }

         public ClaimBuilder WithClaimDate(DateTime claimDate)
         {
              this.claimDate = claimDate;
              return this;
         }
        
         public ClaimBuilder WithProvider(Provider provider)
         {
              this.provider = provider;
              return this;
         }

         public ClaimBuilder WithRecipient(Recipient recipient)
         {
              this.recipient = recipient;
              return this;
         }

         public ClaimBuilder WithClaimLines(ClaimLineCollection claimLines)
         {
              this.claimLines = claimLines;
              return this;
         }

         public static implicit operator Claim(ClaimBuilder builder)
         {
              return new Claim(builder.claimDate, builder.provider, builder.recipient, builder.claimLines);
         }
    }

    As you may note I changed the Build method from the previous post to an implicit operator to save me some coding time when it comes to my builders.  This is one of the very very few places where I'd recommend using this operator.  Anyhow, then we'd have the calling code to look similar to this for my unit tests.

    Claim claim = ClaimBuilder.StartRecording()
         .WithClaimDate(new DateTime(2008, 1, 1))
         .WithProvider(ProviderBuilder.StartRecording()
              .WithName("Robert", "Jones")
              .WithAddress(AddressBuilder.StartRecording()
                   .WithStreetAddress("1800 28th St, NW")
                   .WithCity("Washington")
                   .WithState("DC"))))
         .WithRecipient(RecipientBuilder.StartRecording()
              .WithName(James", "Smith")
              .WithAddress(AddressBuilder.StartRecording()
                   .WithStreetAddress("1210 14th St, SE",)
                   .WithCity("Washington")
                   .WithState("DC"))))
         .WithClaimLines(ClaimLinesBuilder.StartRecording()
              .WithClaim("00308-1")));

    This is truly powerful here to make it make sense to the reader instead of the usual black box ObjectMother approach.  When building my entity objects for test, this is the main approach I use. 

    Other Examples

    Scott Bellware has introduced the Behavior Driven Development NUnit Extensions which makes heavy use of fluent interfaces.  With my deeper dive into BDD, this has been very helpful.  Dave Laribee also has me on the kick as well, so lots of thanks to them for pointing me in the right direction, although some may disagree with their directions.  But that's for another time and another post.

    Jeremy Miller also has fluent interfaces on his StructureMap IOC container project.   Some new parts with registration will be coming up with his new release of version 2.5 as noted here.

    Of course I can keep rattling on with others like NHibernate and the ICriteria, Castle Windsor's fluent registration interfaces and so on.  The list goes on!  Very cool stuff coming out lately...  Until next time!

    kick it on DotNetKicks.com

  • RockNUG Meeting 2/13 - ASP.NET MVC

    The Rockville .NET Users Group (RockNUG) will be holding their Februrary meeting on the 13th at 6:30PM-9PM.  This month, Jeff Schoolcraft will give an introduction to ASP.NET MVC that we have all come to know and love, to a point of course... 

    The details are as follows:

    An Introduction to ASP.NET MVC
    presented by Jeff Schoolcraft

    Come walk with me as I lead you on a gentle, relaxed tour of the ASP.NET MVC Framework. I'll demystify the forest of three letter acronyms. Then we'll take a journey through the hall of ancestors--and cousins--to discuss some influences and other players in the MVC space. We'll end up at the Grove of Hello World and, like habitat for softwarity, we'll build a demo application. Along the way we might run into some tangential trolls, but we'll cross that bridge when we come to it.

    Jeff Schoolcraft is the founder of The Queue, Incorporated; a consulting shop that writes software and helps write software better. He has been in the .NET space from nearly the beginning and is still, mostly, writing web applications in C#. He tries to organize a couple Code Camps a year and is hoping to find a developer community that isn't over an hour away. When he's not immersed in code he enjoys spending time with his wife and two daughters.

    Time:
    Wednesday, February 13, 2007 6:30-9:00 PM

    Location:
    Montgomery College, Rockville
    Humanities Building - Room 103
    Rockville, MD
    Click here for details....

    Come and support the organization if you're in the area!  Should be a great session!

    kick it on DotNetKicks.com

  • Design by Contract Revisited with C# and .NET

    In a previous post, I talked about various attempts at frameworks that are trying to do Design By Contract (DBC) in .NET.  Many simply just come across as simple validation frameworks without the heart of DBC which is the contract.  Where is the contract?  Well, dig through my code and find out!  It's something that I've been harping on time and time again is that without transparency to the caller and callee of the contract, it's just another validation framework.  You'll hear either myself or Greg Young on that, I'm sure.

    The only approach that has worked so far has been Spec# in the .NET world.  Unfortunately, still a research product, isn't available for us to use commercially.  So, until that time in which it is thoroughly weaved into the .NET framework as a whole outside of the internals of System.Core.dll, we have to look at alternatives.

    Eiffel

    Before we look at another framework, I just want to walk you through a sample of the original DBC language, Eiffel.  This gives you an idea what I'm talking about.

    my_list.do_all (agent (s: STRING)
         require
             not_void: s /= Void
         do
             s.append_character (',')
         ensure
             appended: s.count = old s.count + 1
         end)

    As you can see, it's clearly stated as part of the language what the requirements are, and what its return will be.  That's the really slick part about it that we don't have unless we go to Eiffel.NET, but it's not using the latest and greatest .NET APIs, so it's pretty much a nonstarter.  So, let's look at yet another framework.

    LinFu DesignByContract

    Philip Laureano, who has done a lot with LinFu including Aspect Oriented Programming (AOP) among other things has taken a stab at DBC for all .NET languages and not just C# which Spec# has done.  He posted the LinFu.DesignByContract2 article on CodeProject that is well worth checking out. 

    Earlier, he posted one about the LinFu framework on CodeProject as well which includes the following:

    • A simple IoC container
    • Design by Contract framework
    • Dynamic Proxy
    • Reflection (Mixins, Duck Typing and Multiple Dispatch)
    • Delegates with lambdas for universal event handling
    But, let's get back to the DBC part, you'll remember the basic tenets of the philosophy:
    • What do we expect?
    • What do we return?
    • What do we maintain?
    We also throw in a few Eiffel constructs in terms of inheritance which are also quite important.  And they are:
    • The precondition may only be weakened by inheritance
    • The postcondition can only be strengthened by inheritance
    Well, enough about the basics, let's look at the framework itself.  Let's first look at a simple sample I whipped up:

    public class StringCollection
    {
       private int count;
       string[] strings = new string[5];

       [EnsureCountIncremented]
       public virtual void Add([NotNull] string value)
       {
            // NotNull doing
            // Debug.Assert(!string.IsNullOrEmpty(value));

            // Add value and redefine   

            // EnsureCountIncremened 
            // Debug.Assert(count == count + 1);       
       }
    }

    So, what you see here is that I put a postcondition making sure that the count is incremented by one as I'm adding a string to my array.  Also, I have the precondition that my string value is not null.  But, how does that work?

    In order to do that we need to implement a few interfaces.  Let's look at the one for preconditions.

    public interface IMethodContract
    {
        IList<IPrecondition> Preconditions { get; }
        IList<IPostcondition> Postconditions { get; }
    }

    public interface IPrecondition : IMethodContractCheck
    {
        bool Check(object target, InvocationInfo info);
        void ShowError(TextWriter output, object target, InvocationInfo info);
    }

    Ok, so now, I need to implement that somehow for my custom attribute.  That would look similar to this:

    public sealed class NotNullAttribute : Attribute, IPrecondition
    {
         public bool Check(object target, InvocationInfo info)
         {
              string value = target as string;
              if(!string.IsNullOrEmpty(value))
                   return true;
         }

         public void ShowError(TextWriter output, object target, InvocationInfo info)
         {
              output.WriteLine("string value cannot be null or blank");
         }

         public bool AppliesTo(object target, InvocationInfo info)
         {
              return target is string;
         }

         public void Catch(Exception ex)
         {

         }
    }

    So, it's pretty interesting and clever how this is being done.  But still without the static checking of Boogie and so on, it still falls well short of real DBC. 

    For those interested in postconditions and invariants, those are also supported through the interfaces as shown below:

    public interface IPostcondition : IMethodContractCheck
    {
        void BeforeMethodCall(object target, InvocationInfo info);
        bool Check(object target, InvocationInfo info, object returnValue);
        void ShowError(TextWriter output, object target, InvocationInfo info,
            object returnValue);
    }

    public interface IInvariant : IContractCheck
    {
        bool Check(object target, InvocationInfo info, InvariantState callState);
        void ShowError(TextWriter output, object target, InvocationInfo info,
            InvariantState callState);
    }

    So, as I said, quite interesting and clever the way of handling the DBC concepts through interfaces.  The libraries were also written to support the Eiffel constructs of inheritance.  So, very well written I must admit.

    Conclusion

    I just began to scratch the surface with what you can do with this framework and it's very well written.  But, still at the end of the day, it's not statically checked through a Boogie and a theorem prover to ensure the contracts hold.  That's the crucial part missing in this equation.  I'm sure more will come to mind on the subject.  Until next time...

    kick it on DotNetKicks.com