Archive for August, 2009

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.

Fluent Interfaces: How Far is Too Far?

Humor me a moment. I know I’ve promised a series on REST/HTTP/HTML that will likely drive everyone nuts, but I had a thought this morning that is probably more bizarre than many others I’ve had. I have really enjoyed building and using fluent interfaces for tools I’m using. I think they can make the code both more readable and maintainable, though the approach differs from more traditional approaches. I’ve recently been working on a fluent interface for creating Atom items and feeds using the System.ServiceModel.Syndication namespace, and that has been both frustrating and fun.

This morning, however, I had the thought of creating a fluent interface for one of the most simple of concepts used in .NET: collections. What’s wrong with collections you ask? Nothing really. But what if instead of reading

collection.Add(item)

you could read

Add.the(item).to(collection)

? Which is more readable? In the end, that’s similar to what I’m doing with the System.ServiceModel.Syndication bit, except that you don’t generally just add one or a few things to the collection in the syndication example. We could create something similar to add and remove events, all using a single static Add/Remove class with various, overloaded methods for the common identification operations.

Is this overkill? As JB mentioned to me over IM, it’s relative. For some, I’m sure you will think I’m nuts. Others may think I am on to something. I don’t think I would go and do it for no reason at all, but if I ended up with some crazy list creation or end-user-wants-to-read-my-code scenarios, I might consider something like that. What do you think?

MVVM – The no code behind challenge

Glenn Block has an excellent post titled “The spirit of MYYM, it’s not a code counting exercise”. The post can be found at CodeBetter.

I thoroughly enjoyed the post and greatly appreciate practical discussions on WPF/SL application patterns. I am a bit of a WPF nut having lived and breathed xaml for over 2 years. I’ve been a part of 2 successful WPF projects (both in production). In both scenarios I acted as the defacto WPF guru.

This last project was a typical line of business application and we used the ViewModel pattern with Prism. I bring all this up to share my background with WPF and ViewModels.

Concerning the content of the post, I agree with Glenn on the majority of the content. The Commands and Parameters especially rings true. I found that whenever I went with option A [using element binding to a command parameter] I ended up refactoring it to option B [binding the ‘selected’ item to a property on the ViewModel]. Although a neat use of xaml, in practice the binding to the property just allowed more flexibility that indubitable becomes necessary with future changes and demands (not to mention testing opportunities).

With both projects we didn’t have the luxury of a full time designer. In both scenarios I argued there was plenty of work for a designer, but alas the resources just weren’t there. We were able to use a designer for a decent chunk of hours, but more could have been done. The applications were definitely better off for having every hour we could get from any designer resource. I believe the last project persuaded many that indeed there was enough work for a full time designer, so maybe I can hope for a designer with a future application.

I say this because I can not speak towards what its like having a designer in Blend all the time working on Views. When we used a designer resource, they would work in Blend and then a go-between developer / designer would take the xaml and integrate it with our ResourceDictionaries.

What I would like to address is the ‘no code behind’ philosophy compared to the code behind practicality.

Two years ago when I was floundering for WPF information and blogs, I ran across a blog post (I want to say it was Josh Smith) where the writer stated something like : “if something is easier to do in the code behind then its okay to do it in the code behind.”

He was arguing that a crap load of xaml vs a couple lines of code behind isn’t an argument at all. The code behind is the best choice. Naturally clearer intentions and code maintainability takes precedence over having a dogmatic “everything in xaml” approach.

With this last LoB Prism application, we had some choices to make when we were deciding on how the client should be made up.

Do we use UserControls as Views or (as Ryan Riley brought up) do we use Data Templates as views. I felt at the time the team wasn’t ready for that leap to Data Templates as views. I considered the code behind of a User Control as a placebo safety net for a team struggling with the WPF learning curve. What I did do was firmly encouraged a no code behind policy. A “no code behind” challenge if you will.

If I were to go back to the beginning and make that View decision again, I would go with the Data Templates as views. The team did very well without using the code behind. A Data Template view would have brought more benefits than the cost of having no code behind. Often we found ourselves thinking.. if this view was a data template and not a user control, then we could more easier do X.

I have championed the “no code behind” stance internal to Catapult and to other developers. Yes you can legitimately use the code behind to accomplish certain tasks. More often than not though (in my experience), the use of the code behind has more to do with the prejudices carried over from WinForms development. Having a strict no code behind stance forces developers to learn and change the way they think about coding functionality into the UI.

Glenn came up with a scenario (albiet a overly simplified one) of where he felt a code behind had some value. The scenario described is:

‘”The user clicks a Save button on the Edit Order screen which requires some UI cue to the user such as an hourglass while the order is saving, and another cue once the Order has saved.”

He argues that the code in the xaml is less testable. He even suggests the solution I made. He also recognizes others my disagree. Count me in the disagreement camp.

I created a simple project that uses Attached Dependency properties to accomplish this simple scenario. This isn’t a “throw down the gauntlet” sort of thing and I didn’t really write it for Glenn. A coworker emailed Glenn’s blog and I responded in an email describing my solution. He then asked to see it in action. So I coded it up.

He also asked me to post a comment on Glenn’s post, but I don’t really see the point especially since I agree with the information Glenn is sharing and his opinions are built on experience & expertise. I really had no disagreement and the solution Glenn already knows of. /shrug

Anyway.. you can find the solution here : http://github.com/RookieOne/AttachedAnimation/tree/master

The Problem with the MVC Frameworks – Introduction

The anticipatory buzz about ASP.NET MVC last year has become a loud clanging about the general MVC pattern this year. We’ve got several people talking about the “M” in MVC (K. Scott, Rob & Javier); the “right” way to make ASP.NET MVC work (Jimmy and Seb); and complete alternatives in the form of FubuMVC (Front Controller), Bistro (Alex), and—related from a web development perspective if not MVC—OpenRasta (Seb). Why do we have all this complexity or all these options? I submit to you that the problems in the pattern as it relates to web design and the complex structures designed to handle it are a result of mixed metaphors; i.e., the web is not a UI but a service platform.

Before moving on, let me just say that by no means am I advocating WebForms or other, similar frameworks. Such things are atrocities that should never have been committed upon this earth. (Okay, I exaggerate a bit, but hopefully you get my point that while I’m about to rag on MVC, some of these other things are worse.)

As I wrote, this thing became far too long for a single post, so I’m breaking it up into sections. I also need to find and tie in the discussion I had with JB about this very thing. I like how that discussion went, although it was based upon other discussions similar to those in the following posts:

1. A History of Violence against HTML
2. New Names for Old Things
3. Serve me up some of that good ole Appl(ication)e Pie
4. The Web is a Service Bus
5. The Gauntlet

So stay tuned. There’s more to come. :)

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.

Toggling Read Only with WPF

Ayende tweeted a brief code snippet of some WPF he threw together (well I assume he threw it together).

You can see the code snippet here : http://pastie.org/568259

He asked : Someone PLEASE tell me there is a better way than this (WPF)

I tweeted a brief snippet response to improve that tiny bit. The snippet can be found here : http://codesnippets.joyent.com/posts/show/2221

But I couldn’t just leave it at that. I wanted to show a different approach to solving the same problem.

How can we make a control ‘read only’ through binding?

The solution can be found here on my Git Hub Repository : http://github.com/RookieOne/WpfTogglingReadOnly/tree/master

Ignoring all the other machinations, the money xaml is in the TextBoxStyle found in the Styles\TextBoxStyles.xaml resource dictionary.

<Style x:Key="TextBoxStyle" TargetType="TextBox">        
    
    <Style.Triggers>
        
        <DataTrigger Binding="{Binding IsReadOnly}" Value="True">
 
            <!-- Readonly Template -->
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="TextBox">
                        <TextBlock Text="{TemplateBinding Text}" />
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            
        </DataTrigger>
        
    </Style.Triggers>
    
</Style>

As you can see I use the IsReadOnly property on the base view model as a data trigger and then completely swap out the control template for the text box. This allows for complete customization of the read only look. It also pushes this functionality out into a style to be reused through the entire application.

Other things to note with the project (for those unfamiliar with the following practices):

1. Data Templates as Views
<DataTemplate DataType="{x:Type PersonView:PersonViewModel}">

So whenever WPF tries to resolve the PersonViewModel in a container, it will use this DataTemplate since I did not provide a key but only a DataType.

So in Window1 I can do…

<ContentControl>
    <PersonView:PersonViewModel />
</ContentControl>

 
Again this is a very simple scenario so I am ignoring any presentation patterns on how the ViewModel is placed or ‘shown’. Also ignoring how dependencies can be resolved, etc.
 
And even though this is a content control, this works for items controls as well. So consider a stack of ‘views’. You could be accomplish this simply by placing a collection of ViewModels in an ItemsControl.
 
But really… that’s for another post.
 
2. Expression for INotifyPropertyChanged

I am also using a LambdaExpression to implement INotifyPropertyChanged. Essentially achieving safe notification and eliminating those nasty magic strings.

public string FirstName
{
    get { return _firstName; }
    set
    {
        _firstName = value;
        OnPropertyChanged(this, m => m.FirstName);
    }
}

Anyway.. that was a quick project I threw together. I hope it was helpful.