Archive for the ‘Uncategorized’ Category

Examining how we develop software

What I am starting is a mental exercise exploring how my view on software development is changing. Since this is a basically a brain dump, treat it as such. Feel free to comment on what I say… offer advice and opinions. Maybe there is something you can sympathize with.

What has started me thinking along these lines has been my recent readings of The Toyota Way and my re-reading of The Goal.

The Toyota Way
The Goal: A Process of Ongoing Improvement

Both readings have me re-examining my career and software development. Asking questions like, Are we focused on the right things?

Anyway here are the posts:

Named Command Decorator

Here is the problem, we have a list of ‘commands’ we wish to show depending on what view model / entity is active. If we just had a collection of ICommands, we could show buttons but what would their content be?

My solution is to use the decorator pattern to decorate commands with a Name that can be used as the content for the buttons.

My decorator looks like :

public class NamedCommand : ICommand{    public NamedCommand(ICommand decoratedCommand, string name)    {        _DecoratedCommand = decoratedCommand;        Name = name;    }

    readonly ICommand _DecoratedCommand;    public string Name { get; set; }

    public void Execute(object parameter)    {        _DecoratedCommand.Execute(parameter);    }

    public bool CanExecute(object parameter)    {        return _DecoratedCommand.CanExecute(parameter);    }

    public event EventHandler CanExecuteChanged;}

I then created an extension method on ICommand :

public static ICommand Name(this ICommand command, string name){    return new NamedCommand(command, name);}

So in the code I can now do:

Commands.Add(new ActionCommand(OnOpen).Name("Open"));

For my WPF visual, I have a DataTemplate :

<DataTemplate DataType="{x:Type Commands:NamedCommand}" >    <Button Content="{Binding Name}"            Command="{Binding }" /></DataTemplate>

Aop INotifyPropertyChanged StructureMap

Anyone who has worked with INotifyPropertyChanged knows that this simple interface can be a royal pain in the ass.

To try and eliminate the pain, people have created some great solutions using AOP : IL weaving (PostSharp) and using a proxy (Castle Dynamic Proxy).

PostSharp has a little too much voodoo for me atm. I think I will warm up to it though and re-examine using PostSharp on my next solution. But for now, I wanted to use Castle Project’s Dynamic Proxy.

Naturally since Castle also has a very popular IoC container in Windsor, most examples marry Dynamic Proxy and Windsor to form an AOP INotifyPropertyChanged solution.

Since I am using StructureMap for this project, I endeavored to create my own solution using Dynamic Proxy.

My first attempt I shared at the Virtual Brown Bag look liked it worked but in reality I was constructing my objects twice.

Once with SM and once with the Proxy generator.

I had to go back to the drawing board and posted my problem at the SM google group. http://groups.google.com/group/structuremap-users/browse_thread/thread/1a6b19ce8152db1b?hl=en

I believe the syntax given to me was an older version of SM. For the record, I am using version 2.5.3.0

But it did direct me to the general idea on where I should start looking. I ended up needing to create an IBuildInterceptor.

public class MyBuildInterceptor : IBuildInterceptor   {       public MyBuildInterceptor(Type concreteType)       {           _ConcreteType = concreteType;       }

       readonly Type _ConcreteType;

       public object Build(BuildSession buildSession, Type pluginType, Instance instance)       {           var constructorArgs = _ConcreteType               .GetConstructors()               .FirstOrDefault()               .GetParameters()               .Select(p => buildSession.CreateInstance(p.ParameterType))               .ToArray();

           var interceptors = new List<IInterceptor>                                  {                                      new NotifyInterceptor()                                  }                                  .ToArray();

           return new ProxyGenerator().CreateClassProxy(_ConcreteType, interceptors, constructorArgs);       }

       public IBuildPolicy Clone()       {           return InnerPolicy.Clone();       }

       public void EjectAll()       {           InnerPolicy.EjectAll();       }

       public IBuildPolicy InnerPolicy { get; set; }   }

To register my ViewModels I created a convention using a TypeScanner

public class MyNotifyConvention : ITypeScanner{    public void Process(Type type, PluginGraph graph)    {

        if (type.GetInterface("IViewModel") == null)            return;

        var interfaceType = type.GetInterfaces().FirstOrDefault(i => i.Name.Contains("ViewModel")                                                            && i.Name != "IViewModel");

        if (interfaceType == null)            return;

        graph.Configure(r =>                        r.ForRequestedType(interfaceType)                        .InterceptConstructionWith(new MyBuildInterceptor(type))                        .TheDefaultIsConcreteType(type));    }}

I then used a Dynamic Proxy Interceptor that I basically copy and pasted from Serial Seb’s example.

public class NotifyInterceptor : IInterceptor{    public void Intercept(IInvocation invocation)    {        // let the original call go through first, so we can notify *after*        invocation.Proceed();

        if (invocation.Method.Name.StartsWith("set_"))        {            string propertyName = invocation.Method.Name.Substring(4);            RaisePropertyChangedEvent(invocation, propertyName, invocation.TargetType);        }    }

    void RaisePropertyChangedEvent(IInvocation invocation, string propertyName, Type type)    {        // get the field storing the delegate list that are stored by the event.        var methodInfo = type.GetMethod("RaisePropertyChanged");

        if (methodInfo == null)        {            if (type.BaseType != null)                RaisePropertyChangedEvent(invocation, propertyName, type.BaseType);        }        else // info != null        {            methodInfo.Invoke(invocation.InvocationTarget, new object[] {propertyName});        }    }}

Instead of looking for the PropertyChanged Handler, I create a RaisePropertyChanged method and use that. Although I could raise the event using the field method Seb was using, WPF wasn’t updating the binding. I didn’t really bother to investigate and just rolled with this solution.

So that’s my solution and I’ll start using it in my current solution. Naturally I will clean up the code some more etc. Feel free to use this for any of your own projects. You can also get the solution at my GitHub:

http://github.com/RookieOne/StructureMapAopNotify

Monads.

Ryan is the monad king. Ok.. well maybe not the king. But he has a big megaphone and drops a ‘monad’ bomb daily. He has been doing some fantastic work in F# and C# using monads. He shares his code and I just stare… going WTF is this!

I know the basic concepts of what a monad is mostly due to random discussions. I never put any solid research time into what it is… why I would use it… and where does it fit into the larger scheme of my personal development toolkit.

I started my adventure in learning where I normally start… wikipedia.

http://en.wikipedia.org/wiki/Monad_%28functional_programming%29

Whoa.. lots of new terms thrown at me. Here are some random notes and crazy thoughts I am pulling out (mostly for myself).

“a monad is a kind of abstract data type used to represent computations (instead of data in the domain model)”

That sparks some ideas. Anyone who talks to me on a regular basis knows I am a huge Greg Young CQS fan. I think I’ve always been circling around these ideas but Greg’s insights just pulled away the haze and brought into focus the essence of what always bothered me.

For more information on Greg Young’s CQS, I would suggest http://jonathan-oliver.blogspot.com/2009/03/dddd-and-cqs-getting-started.html

Jonathan has compiled a great set of links to get introduced to the ideas. I am by no means an expert, but I consider myself a CQS disciple. :)

Back to monads.

The idea of the ‘domain’ being a ‘computation’ or ‘action’ more than data makes me think there might be a connection to explore.

“Monads allow the programmer to chain actions together to build a pipeline, in which each action is decorated with additional processing rules provided by the monad.”

This makes me think of the ‘reconstruction’ of a domain object by processing its events. That would be a neat POC to put together.

“The return operation puts a value from a plain type into a monadic container of type M. The bind operation performs the reverse process, extracting the original value from the container and passing it to the associated next function in the pipeline.”

I am still unclear on the whole wrapping business. I think I will revisit this again after going to another location to learn about monads.

So I moved over to Channel 9 and began to watch:

http://channel9.msdn.com/shows/Going+Deep/Brian-Beckman-The-Zen-of-Expressing-State-The-State-Monad/

Here are some random notes / quotes:

“Only two types of variables. A bound variable and a free variable. Bound variable is a function argument. A free variable has to be looked up somewhere else.”

State monad takes a state and spits out a state, content pair.

“Composition is good” :)

“Mathematics is the art of abstraction and precision”

Is functional programming and monads a disruptive technology? Although it technically isn’t that ‘new’. I think it might be. The comments around an army of OO programmers and the difficulty for learning to think functionally just resonates with the idea that functional programming is a disruptive technology (even though functional programming isn’t new).

Ok… That was a pretty rough first day. Lots of terms and pictures and strange code thrown my way. It’s time to process the information. I’m pretty sure I will need to watch that video about 5 times in-between coding this stuff. I plan on trying Brian’s exercises along with watching ‘Don’t Fear the Monad’ (another Brian Beckman presentation).

Ryan already has completed the first exercise in C# and F#. I will work on my own version of the C# exercise and then look at his code. I don’t think I will dive into F# right now. I played with the language about 2 weeks ago but all I did was create ‘Hello World’. There is a F# user group meeting on August 27th where I ‘might’ try to code these exercises.

What is Code Quality?

Since I was young, my father has encouraged me to become a writer, so a few years ago, I entertained the idea, and bought a book by Stephen King called “On Writing”. From it, I learned several aspects of good writing. One of the most memorable was to avoid adverbs ending in -ly. The reason they should be avoided is because your verbs, nouns and adjectives should describe your intentions without the use of adverbs. Adverbs are extra fluff, and when overused, are the mark of an immature writing style.

Until I read that book, I never thought about the importance of one sentence. A good novel writer ensures that his audience is not subjected to needless modifiers that serve to support poorly written sentences. Not only this, but he does it on a consistent basis, one sentence at a time, until the entire novel is written, all the while focusing on the overall plot of the book. The mark of quality in a novel is it’s ability to move the plot forward while avoiding unnecessary distractions. This hallmark is established with each and every sentence.

In the publishing world, there are checks and balances to ensure that before a novel is released, the quality of the novel matches up to certain standards. After the novelist writes the novel, he sends the manuscript to the publisher, who typically suggests one or many edits that the manuscript needs before it’s ready to be published. The novelist then edits his manuscript and repeats this process until the book is ready to publish.

Now, liken yourself to a novelist. You have a novel (your code) full of sentences (lines) that you’re tasked to write. The assumption is that you will not only focus on the purpose of the application, but will also focus on how that purpose is to be achieved, by paying attention to each and every line of code. I’ve heard it said recently that “it only takes one line to create a dependency”. This statement shows the power that one line of code can have. It can make or break your application.

So what is code quality? Quality code can only come from paying attention to each line you write. As I’m writing this blog, I’m paying attention to each and every sentence I write. I’m reviewing each one to verify they communicate my point clearly and concisely. The reason I’m doing this is because I know there are people who will read this post. They’ll analyze what I’m saying, and won’t want to waste their time while reading it. They expect to learn something from every sentence.

So why don’t we do this as much in our code? I think it’s because we believe that our code will never be read. It will only be used. This is a false assumption that needs rejecting. Every day I read the code I’ve read in order to modify it, or in order to hunt down a bug. The way the code is written is almost as important as what it does. Poorly written code takes longer to maintain. Well written code can be maintained almost effortlessly.

Each line of code should serve a purpose. Each set of lines should be reviewed as it’s being written, to ensure the most clear and concise expression of the concept is found. Each architectural construct should be reviewed for it’s flexibility and it’s contribution to the overall goal. This should happen not in a designated refactoring session, but during the moment-by-moment process of coding.

This takes patience, consistency and the ability to clearly adhere to and express the purpose.

Code quality, in my definition, is a well-assembled collection of well-expressed lines of code, none of them being taken for granted. This is a basic concept, but one that needs reinforcing from time to time. There are so many concepts to quality programming that it takes a lifetime to master them all (if indeed they can be mastered), but for a good start allow me to suggest SOLID principles and design patterns. Professional programmers will learn these techniques and use them to their advantage. Poor programmers will abuse the code and muddle it’s intentions.

Refactor in the small, and refactor consistently as you go. A good place to start might be to begin reading Sean Chambers’ current blog series entitled 31 Days of Refactoring. Refactoring as you go can help to prevent technical debt.

Learn these techniques and apply them as you go, not after the fact, and you’ll find at the end that your code can be as enjoyable to read as some of the world’s greatest authors, from Hemingway to King to Rowling.

Write code like it’s going to be read.

Another Oxite Indeed

Another Oxite, indeed. My Google Reader reported a flood of activity in the AppArch CodePlex wiki, the majority of which was updated patterns pages with “BETA – Published for Community Feedback. This page is a wiki.  Please provide your feedback in the comments below,” at the top. The Application Architecture Guide, v2 is now back in beta status after the flood of community feedback following its December 2008 “final” release.

I’m glad to see Microsoft respond to the community. I find great hope in Microsoft’s future in their willingness to listen and respond. If only they would do so sooner rather than later, they would have a much better reputation with the community. Nevertheless, I’m pleased with their desire to dialogue with the community to improve their guidance.

Now, if you are an architect or developer with experience in the areas for which Microsoft is offering guidance, speak up. Help provide the response for which Microsoft is asking. This is a great opportunity for us to bridge the relationship we have with the team at Microsoft providing the tools we use daily.

Coding, Blink, and the Smell Test

I’ve recently been assigned a complicated use case and have been heads down working on finishing it up.

Mostly its been a great exercise in BDD requirements / story construction. I’ve stumbled, made mistakes, corrected mistakes, etc

I am still excited about BDD stories. I think with DDD and BDD and insert jargon here… there is a drive to pass the infamous smell test.

There are the developers that just code. They apply a technology and just swing code around to solve a problem. Comments and best practices and solid design be damned. It works! So what’s the problem?

Then there are the developers that have that passion and instinct to know something is wrong. The idea is similar to Gladwell’s Blink principle. These developers first just code and refactor in solo. I relate it to a ronin samurai. Maybe a Luke Skywalker before his time with Yoda. ;)

They then discover patterns and OMG.. the lights go on and you have an epiphany. There is a great book on font design by Robin Williams called The Non-Designer’s Design & Type Books. Chapter one is called The Joshua Tree Epiphany. Here is the quick summary. She picked up a tree book and the first tree was the Joshua Tree. She said to herself, “Oh, we don’t have that kind of tree in Northern California. That is a weird-looking tree. I would know if I saw that tree, and I’ve never seen one before.” She then went outside and immediately saw that her neighbors had Joshua trees. Yet she never ‘saw’ one before because she didn’t know what they were. This principle she describes simply saying :

*Once you can name something, you’re conscious of it. You have power over it. You own it. You’re in control.*

Once developers are exposed to patterns and understand patterns, a new world is opened up to them. And beyond patterns, there are principles. I recently listened to the Hansel Minutes with ‘Uncle Bob’ on the SOLID principles. I found myself saying.. exactly! a lot. The principles just resonate ‘rightness’.

Anyway, what I am trying to say is that on the road to becoming the best developer I can be, I am at the mastering DDD / BDD / TDD stage. I know they are right because when I execute them correctly, it feels right. When I mess things up, it feels wrong. In lots of ways it feels like I am on an intellectual adventure. Maybe like Lord of the Rings. Instead of the ring weighing down Frodo the closer he got to Mount Doom… the closer I get to mastery of these concepts the better I feel about development.

So anyway.. those are some random thoughts I’ve been having lately. Hence the low number of blog posts. I’ve been using the time to read (because I need to catch up!) and to practice the esoteric art of BDD stories. My current reference is Dan North’s site.

I will update Greek Fire soon with documents mostly. I want to have a readme file about setting up the database. I also want to have BDD stories to document the requirements for the domain, etc.

How do I hide columns with a Wpf GridView?

In my current project we ran across a problem where we wanted to hide certain columns in a grid view based on domain criteria.

We looked into custom grid headers, attached properties, custom controls, etc. Every path lead to a very complex and more importantly custom solution.

I spent an afternoon playing around and came up with this solution which we are using today.

It’s simple, easy to follow, and doesn’t require any custom code. All it uses is the power of style and triggers. The biggest knock is OH NOES! you have a bit of duplication in your xaml.

What is it?

Well, you set the ‘View’ property in your style. Then you utilize style triggers to swap out the View.

Yup.. easy.. simple… no mess.

Example :

<style x:Key="listViewStyle" TargetType="ListView">
    <setter Property="View">
        </setter><setter .Value>

            <gridview>
                <gridviewcolumn Header="Name"
                                DisplayMemberBinding="{Binding Name}" />
                <gridviewcolumn Header="Salary"
                                DisplayMemberBinding="{Binding Salary}" />
            </gridview>

        </setter>

    </style><style .Triggers>
        <datatrigger Binding="{Binding HideCols}" Value="True">

            <setter Property="View">
                </setter><setter .Value>

                    <gridview>
                        <gridviewcolumn Header="Name"
                                        DisplayMemberBinding="{Binding Name}" />
                    </gridview>

                </setter>

        </datatrigger>
    </style>

Repositories and Presentation

I recently came upon a question in the Domain Driven Design Yahoo! Groups asking whether or not the presentation layer should interact directly with repositories or through a method on the entity (domain model). Having just finished Nilsson’s Applying Domain Driven Design Patterns and (finally) getting my head around LINQ to SQL on my current project, I decided to weigh in on the matter.

As always, it depends. You can indeed allow the presentation layer to use the repository directly, just as you can allow the presentation layer to use a factory to create your entities. Your current implementation is something I started off with when I started trying to do DDD, and follows more of the Active Record pattern, as mentioned by another responder, thought Active Record, by definition, matches the database table field for field.

You have several options:

  1. Use your current approach. You’ll probably need to merge your repository and entity by using static methods and properties, though, which can make it messy, and I wouldn’t recommend it. That’s why I stopped using this approach, anyway.
  2. Add a validation mechanism to your repository to validate your entities or, if your entities validate themselves, report the entities’ validation before you save.
  3. If you really like the Save method on your entity and you use .NET or a dynamic language (not sure about other platforms), you can use extension methods to “add” a Save method that wraps a call to your repository. This is really option 2 with some syntactic sugar.
  4. BEST PRACTICE (?): Use a Unit of Work, such as LINQ to SQL’s DataContext, Entity Framework’s ObjectContext, or NHibernate’s / SubSonic 3’s ISession to manage transactions and repsoitories, then call SubmitChanges() through the unit of work.

The Unit of Work pattern can be a little hard to understand at first, but it is quite powerful and great for managing rollbacks (which are extremely difficult if you always wrap your unit of work/repositories in the entity methods).

For reference, try these links:
http://iridescence.no/post/ASPNET-MVC-DataContext-and-The-Unit-of-Work-Pattern.aspx
http://www.west-wind.com/weblog/posts/246222.aspx

For keeping LINQ to SQL and Entity Framework persistence ignorant (PI), see:
http://iancooper.spaces.live.com/blog/cns!844BD2811F9ABE9C!397.entry
http://code.msdn.microsoft.com/EFPocoAdapter

Double Click Command Behavior

I recently posted how to bind an ICommand on a ViewModel to an Input binding.

I thought I would also add a post sharing an attached dependency property I use to binding ‘double click’ to an ICommand.

The xaml to use the behavior looks like : (naturally where Behaviors is my xml namespace, etc)

&lt;ListBox Style=&quot;{StaticResource ListBoxStyle}&quot;
 SelectedItem=&quot;{Binding SelectedItem}&quot;

Behaviors:DoubleClickCommandBehavior.DoubleClickCommand=&quot;{Binding EditCommand}&quot;

ItemsSource=&quot;{Binding Items}&quot;
 ItemTemplate=&quot;{StaticResource Template}&quot;&gt;
&lt;/ListBox&gt;

What follows is the code. Enjoy! – JB

   1: /// <summary>
   2: /// Double Click Command Behavior.
   3: /// Is a attached dependency property where you attach a command to execute upon the dependency object
   4: /// (control) being 'double clicked'
   5: /// </summary>
   6: /// <remarks>created by Jonathan Birkholz 7/21/08</remarks>
   7: public static class DoubleClickCommandBehavior
   8: {
   9:     #region Double Click Command Property
  10:
  11:     public static readonly DependencyProperty DoubleClickCommandProperty =
  12:         DependencyProperty.RegisterAttached("DoubleClickCommand",
  13:                                             typeof(ICommand), typeof(DoubleClickCommandBehavior),
  14:                                             new PropertyMetadata(null, DoubleClickCommandChanged));
  15:
  16:     public static ICommand GetDoubleClickCommand(DependencyObject obj)
  17:     {
  18:         return (ICommand)obj.GetValue(DoubleClickCommandProperty);
  19:     }
  20:
  21:     public static void SetDoubleClickCommand(DependencyObject obj, ICommand value)
  22:     {
  23:         obj.SetValue(DoubleClickCommandProperty, value);
  24:     }
  25:
  26:     #endregion
  27:
  28:     #region Double Click Command Parameter Property
  29:
  30:     public static readonly DependencyProperty DoubleClickCommandParameterProperty =
  31:         DependencyProperty.RegisterAttached("DoubleClickCommandParameter",
  32:                                             typeof(object), typeof(DoubleClickCommandBehavior),
  33:                                             new PropertyMetadata(null));
  34:
  35:     public static object GetDoubleClickCommandParameter(DependencyObject obj)
  36:     {
  37:         return (object)obj.GetValue(DoubleClickCommandParameterProperty);
  38:     }
  39:
  40:     public static void SetDoubleClickCommandParameter(DependencyObject obj, object value)
  41:     {
  42:         obj.SetValue(DoubleClickCommandParameterProperty, value);
  43:     }
  44:
  45:     #endregion
  46:
  47:     #region Double Click Command Changed
  48:
  49:     private static void DoubleClickCommandChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
  50:     {
  51:         Selector selector = obj as Selector;
  52:
  53:         if (selector != null)
  54:             selector.PreviewMouseLeftButtonDown += HandlePreviewMouseLeftButtonDown;
  55:     }
  56:
  57:     private static void HandlePreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs mouseEventArgs)
  58:     {
  59:         if (mouseEventArgs.ClickCount == 2)
  60:         {
  61:             DependencyObject depObj = sender as DependencyObject;
  62:
  63:             if (depObj != null)
  64:             {
  65:                 Selector selector = depObj as Selector;
  66:
  67:                 if (selector != null)
  68:                 {
  69:                     if (selector.SelectedItem != null)
  70:                     {
  71:                         ICommand command = GetDoubleClickCommand(depObj);
  72:                         object commandParameter = GetDoubleClickCommandParameter(depObj);
  73:
  74:                         command.Execute(commandParameter);
  75:                     }
  76:                 }
  77:
  78:             }
  79:         }
  80:     }
  81:
  82:     #endregion
  83: }