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

Christopher Bennage

Musings and revelations on C#, .NET, and other related technologies.
  • The Roots of Best Practices

    I've been asked about best practices and good design several times over the last few months. A few questions have been from students, or newcomers to .NET, and I have found their questions very insightful. They ask questions I remember asking myself. One good example was "I know I should separate my app into three layers, but how should I do it?"

    Getting to the RootsI'm rather to sensitive to the idea of "answering the wrong question". I believe that it's easy to do that when talking about best practices.  My intention with this post is build a foundation for discussing good design. A starting point to make sure we are solving the right riddle. I certainly don't consider myself a master on this topic, but I do have a lot of thoughts.

    Acknowledging My Bias

    I'm a fan of Object Orient Programming, Domain-Driven Design, Design Patterns, Test Driven Development, and agile methodologies. I use a lot of open source software, and I'm ALT.NET. Foremost, I like to think that I am pragmatic.   I'm motivated by getting stuff done.

    The Point of Best Practices

    There are a long list of principles out that are generally acknowledged as best practices. They range from generalities like "your code should be well commented" to very specific and named rules such as the Liskov substitution principle. Regardless of the type, I think it's important to know why a given principle is better than its alternatives.

    I'll use the Law of Demeter (LoD) as an example. Overly simplified, the law says that an object should only invoke methods that it owns.  In other words, you'll break the law with something.child.Method() whereas something.Method() does not. 

    Why is LoD good? One quick answer is that you never know when something.child might be null, and applying LoD helps you avoid the nasty NullReferenceException. Wikipedia has a nice summary the benefits:

    The advantage of following the Law of Demeter is that the resulting software tends to be more maintainable and adaptable. Since objects are less dependent on the internal structure of other objects, object containers can be changed without reworking their callers.

    Now we are approaching the real heart of the matter, we want software that is easy to maintainable, and easy to extend. LoD promotes those values. In facts, most of the generally accepted principles are meant to produce software that is maintainable and extensible. Here is my Grand Unification Theory of software best practices: the guiding, or root, principles are Maintainability and Extensibility. (These two are close cousins, and you might arguably combine them.)

    The Root of the Matter

    Now, let's deconstruct further.  Why do we care about Maintainability and Extensibility? We care because they result in reduced costs.  The bulk of cost with custom software is not building it, but maintaining it. If you are in business, reduced costs equals more money; if you are a hobbyist or open source developer then reduced costs means getting to the desired result in less time.  That's the bottom line: time and money. We employ best practices to save ourselves time and money.

    Okay, well, nothing new here. You probably already knew this.  I emphasize it though because I've found that "best practices" have a tendency to degrade into a set of arbitrarily applied rules, enforced without exception, irrespective of whether or not they are useful. A great example is "always comment your code". The intention of this rule is improve maintainability.  We've all seen the end result.

    //open the file 
    FileStream stream = File.Open(pathToFile, FileMode.Open);

    Does this improve maintainability? Perhaps if you can't read C#, but even then it seems unlikely. Does one extraneous little comment hurt? Not by itself. A poppy flower is beautiful, a thousand poppies is dangerous. If 50% of your source is extraneous comments, it's nothing but noise and it's reducing maintainability.

    My Point

    Let's take a look at the question I was asked again:

    "I know I should separate my app into three layers, but how should I do it?"

    To answer this correctly, we need to start with the motivation for layering an application in the first place. "Three-tier architecture" has a good intention, just as "well commented code" does. However, the principle has can easily be lost in the arbitrary application of the rule.

    In a soon-to-follow post, I'll examine this specific question of layering an application from its roots.

    Epilogue

    For some reading in the meantime, check out the series of posts over at Los Techies on SOLID Principles. There is some great discussion in the comments too.

    What do you think?

  • Thoughts on ALT.NET

    I just listened to Scott Hanselman interviewing Dave Laribee regarding ALT.NET. I really like what Dave had to say, and I encourage everyone to go and listen.  I've been reticent about the ALT.NET movement (aside from my initial surge of enthusiasm.) I'm a bit shy when it comes to controversy, and even though I have strong evangelistic tendencies, I am also quick to shut up. ALT.NET has had its share of controversy.

    Now we're an institution!I really like that Dave said it's not about the tools, it's about the principles.  I am frequently asked about "good design" and "best practices".   This is why I'm ALT.NET. (In fact, I have a series of posts on this topic that I intend to start after we're done with the book.)

    There's an item in the interview that I'd like to comment on.

    Scott asks (pardon my paraphrasing) why would the hypothetical Chief Architect of the Nebraska Department of Forestry have any interest in ALT.NET? The mythical Mort has pressing concerns, he just needs to get work done, why would he care about these conversations, discussions, and principles? Listen to the podcast for Dave's answer.  However, my answer is this: he probably doesn't care and that's okay. I think that ALT.NET is about bringing good design and principle to the forefront.  However, good ideas take a while to be adopted, to be democratized.  Those who are hungry, we'll feed.  Those who aren't, we'll wish them well.  No hard feelings. Eventually, the good ideas will be institutionalized and they'll trickle down. (Have you noticed the "refactor" menu in Visual Studio?) I'm more concerned about convincing the institutions and the thought leaders.  (Perhaps "convincing" is the wrong word, ALT.NET is more about "conversing" to me.) That's why it's good that ALT.NET is conversing with Microsoft, and that's also why I'm encouraged to see Microsoft paying attention to things like open source (though I know many people are angry about the kind of attention being paid).

    Now go learn Ruby!  :-)

  • Identifying Control Templates Parts in WPF

    I'm currently writing the chapter about control templates in our WPF book, and I wanted to include a list of all of the named parts that are hidden away in the dark recesses of the various controls.  Before I even started googling, I had an idea that I thought I'd share.

    For those of you not yet familiar with control templates, WPF allows you to redefine the visual appearance of controls. The problem is that some of the controls have special named parts, that is, there are visual elements with specific names that the code expects to be there.  Luckily, there is the TemplatePartAttribute that's meant to decorate controls with named parts. If you look at the documentation for a given control, the attributes are listed and you'll know what named elements a new template requires.

    Given an assembly though, it's quite easy to identify the controls programmatically. Here's some C# that does just that:

    using System;
    using System.Linq;
    using System.Reflection;
    using System.Windows;
    using System.Windows.Controls;
    
    namespace TemplatesParts
    {
        class Program
        {
            static void Main()
            {
                var assembly = Assembly.GetAssembly(typeof (Control));
                var attributeType = typeof (TemplatePartAttribute);
    
                var controls = from c in assembly.GetTypes()
                               where c.GetCustomAttributes(attributeType, false).Length > 0
                               orderby c.Name
                               select new {c.Name,Parts=c.GetCustomAttributes(attributeType, false)};
    
                foreach (var control in controls)
                {
                    Console.WriteLine(control.Name);
                    foreach (var part in control.Parts)
                    {
                        Console.WriteLine( "   " + ((TemplatePartAttribute)part).Name);
                    }
                }
                Console.ReadLine();
            }
        }
    }
    

    Now, if I can just look this up in the documentation, why bother with this code? It was fun, what can I say?

  • Discovering Empty Try/Catch Blocks

    I've been burned by a few bugs recently due to swallowed exceptions.  In case you don't know, empty catch blocks will hurt you. Really, they will.

    I wanted a way to locate all of the empty blocks in our code base, I was playing around with NDepend and the amazing Code Query Language, but it's not able to do something like this yet.  (Patrick said that it will in the next version!)

    Then I realized that I was missing the simple solution. The Find and Replace dialog in Visual Studio.Ctrl+F and a regular expression!

    Here is the regex you'll need to find empty catch blocks in your solution:

    catch:Wh*\{:Wh*\}

    ":Wh" designates whitespace

    * means zero or more

    You have to escape the {} as they are special characters.

    Update: Note Dan's comments below. Here's an updated regex to cast a wider net:
    catch(\(.*Exception.*\))*:Wh*\{:Wh*\}
  • VS2008 Demo Challenge

    Last week or so, I stumbled on to the site for the Visual Studio 2008 Demo Challenge. The gist of the contest is to make a video explaining why VS 2008 is great, and then win stuff. Your video is played backed in a Silverlight app that your host at silverlight.live.com.

    So I make a video, and I think it's pretty funny.  I setup an app with Expression Encoder, and I'm feeling great.  I go to submit the video on the contest site and ... nothing. The site seems broken, which would explain the lack of videos in the gallery. (I had a bad feeling about the absence of competition.)

    I just don't have good luck with Microsoft contests. :-(

    Click here to watch the video. You'll need Silverlight 1.0 to view it.

    Update: I just heard that the contest died. Would someone still like to give me an Xbox for kicks? :-)

  • The Words We Use

    I just read this great post by Jimmy Bogard over at  Los Techies. He talks about user stories and the fact that what you call a user story is very important. (A rose by another other name would not smell as sweet. ) Words affect how we think about things; though we don't like to admit it.  I've definitely struggled with this myself.

    If you ever communicate with your clients, then I recommend checking out the post.  It's short too.

    I particularly like his comment that prioritizing a requirement is like putting lipstick on a pig.

  • XAML Only WPF Example (Font Viewer)

    The very first application I attempted to write in WPF was a utility to help me with choosing fonts. I'm a developer who has one foot in the designer world, and I am always looking for just the right font. I think that was about 2 years ago, and I was ecstatic that my prototype application took about 15 minutes to write and contained 3 or 4 lines of code (that's not counting the XAML markup.)

    When Rob and I began outlining our upcoming book on WPF, we decided to structure the it around four example applications.  The font viewer seemed like a natural choice for the first application because it's so simple to write., and easy to understand.  I showed the source to Rob, and in less than 10 minutes we had a 100% XAML version of the application. Yes, we removed those troublesome 3-4 lines of code.  :-)

    I decided to play around with it some more, and here is the result. It's a 24KB text file containing just XAML.  If you have .NET 3.5 installed, it should execute in your browser (both Firefox and Internet Explorer work).  It's a very simple application, but I think it's fun. I'm especially fond of the built-in tutorial (be sure to click the help icon).

    This version is a lot more complicated than the one we build in the book.  We don't introduce the concepts of styles, templates, animation, etc until after we're done with the font viewer. 

    In a nutshell, here is how it works. The list box is bound to the set of installed fonts on your system (System.Windows.Media.Fonts.SystemFontFamilies). There are series of four text blocks, whose font family is bound to the selected item on the list box.  Finally, the four text blocks get their content from the text box at the bottom. That's it.

    Please feel free to analyze, dissect, assimilate as you like.  You can get to the source using your browser's "view source" feature.

    Disclaimer: Only very recently did I bother to see if anyone else had done the same thing.  Yes, they had, and more.

    Bonus Question: How would you handle building an application like this with TDD\BDD? How does declarative programming collide with TDD\BDD?

  • You should blog++

    Jeremy Miller recently posted a general encouragement to blog. I'll add my voice to his and as well as confess that I have avoided posting sometimes out of fear of being stupid.  The truth is, I am stupid.  But blogging helps me unstupid, so I'm deliberately posting more.

    Francis Bacon said:

    Reading maketh a full man, conference a ready man,
    and writing an exact man.

    Participating in the blogosphere covers all three.

    Oh, here's some more bacon.

  • Beatriz Costa: Debugging WPF Binding

    If you are WPF developer and you are not familiar with Costa's blog, you should really check it out.  Lots and lots of good posts about data binding in WPF.

    The most recent post is about debugging data binding, which has been a personal pain point on recent projects. (Really it was more testability, than debugging, but that exact problem isn't solved yet.) Anyway, Beatriz offers several options for debugging bindings, go check them out.

  • My Development Tools

    The last two Octobers, I took a moment to reflect on the development tools I was using.  It's interesting to see what sticks, and what doesn't.  Unfortunately, my 2005 list is lost in the aether, but here is the link to 2006, and more importantly the list from last year...

    Tools I Really Used in 2007:

    • ReSharper, a productivity enhancer for Visual Studio and often referred to as R#.  I've preached the virtues of the product many times before.  Unfortunately, it's not ready for VS2008 as many have lamented iStock_000003150423XSmalland many have criticized.  But, when it is you better watch out!

    • SQL Prompt from Red Gate. Amazing IntelliSense type behavior for SQL as well as your custom schemas.  Makes me wish I was doing more SQL work sometimes. I also use their SQL Compare and SQL Data Compare products frequently to sync up databases.

    • Subversion, often referred to as SVN. This has been my source control of choice for the last four years.

    • TortoiseSVN, SVN client for Windows. I still use this, but I am enamored with...

    • VisualSVN, a Visual Studio plugin for integrating SVN. Well worth the money.  It has made using SVN in Visual Studio effortless.

    • TopStyle, an excellent CSS editor that has been in my toolbox for years now.

    • Firebug, an essential for Web developers! Did I mention that it is essential?

    • Unfuddle, a lot like BaseCamp (which we continue to use).  It's a project communication app with integrated SVN.  It fills a gap that BaseCamp misses, providing "tickets" for tracking bugs, change requests, etc.  However, there are still some things BaseCamp is better at.

    • MbUnit, my xUnit testing framework of choice.  I really like MbUnit, though R# support has been weak.  (I think it's was R# 3.0's fault though).

    • NHibernate, the darling object-relation mapper (O\R M) for .NET. This really simplifies data access a lot.  However, getting started can be a barrier. Our own Billy can help you out though.

    • Rhino.Mocks, a mocking framework for doing TDD/BDD.  I have really enjoyed using this (after I was able to grok it).  I will confess though that all of the controversy about TypeMock has peaked my interest.

    • Castle\MonoRail, we had our first big MonoRail project.  So we spent about 3 months really working with MonoRail.  I don't care to ever see an ASPX page again. We have also been using Windsor in a complicated WPF application.

    • Prototype and Scriptaculous, two related JavaScript frameworks.  MonoRail has some built-in support for these, and they are prevalent in the RoR community.  I have been very impressed and pleased with both, though some recent reading is leading me to consider jQuery.

    • EditPlus, I'm wandering if maybe I am stuck in my old ways here.  I know that there are lots of text editors out there.  I've been using this one for about 8+ years.  It's fast, and easy though.  Any suggestions?

    • Adobe Flash CS3, try as I might, I always seem to end up with a Flash project. So while I'm making this confession, I should also list...

    • FlashDevelop, a free, open-source IDE for ActionScript written in .NET.  This along with some related tools has made Flash\ActionScript much less painful.

    • .NET 3.0, we made heavy use of WPF and WCF on a major project. We were really excited about the results, and fortunately the client was pleased and they are bring us back for more in 2008.

    • Expression Blend 2.0, for editing XAML for WPF.  Even though 2.0 isn't released I found it superior to 1.0.  I can't say that I am ecstatic with this tool, it has its flaws, but think it is headed in the right direction.

    • Draco.NET for continuous integration.  I found it much easier to setup that CC.NET.  See my post about it here.  I am recently interested in TeamCity

    • Lutz Roeder's Reflector, I've solved a lot of problems though decompiling (even my own assembly once!)

    I could go on, and on, but this list is getting pretty lengthy.  So now, contribute! What are your tools?

  • Phil Haack: Research on TDD

    Phil Haack has an interesting post on some research regarding the effectiveness of Test Driven Development. I'm really glad to know that this sort of work is going on, and the results are, er, moderately encouraging to the TDD enthusiast. This topic of research supporting methodologies has been a bit contentious of late. These subjects seem like they would be very difficult to analyze because there are some many factors involved (from skill level of the individual developers to the qualification of 'what good code is'.) Nevertheless, carry on my good researchers!

    Now, I want to hook up with a CS department. Anyone out there from the FSU CS department reading this? :-)

  • 42m is not a constant

    Here's a little CLR tidbit I picked up today while writing a [RowTest] with MbUnit.

    If you want to specify a decimal value in C#, you add the suffix m or M.  You can read all about it here.  This means you might have something in your code  like this:

    decimal myBigMoney = 19.95m;

    Well, it turns out that 19.95m is not a constant value, it's actually shorthand that the compiler translates to

    decimal myBigMoney = new decimal(19.95);

    and "decimal" is an alias of the struct System.Decimal. This means that you can't pass the value 19.95m as an argument into an attribute, like this:

    [RowTest(19.95m)]

    (because attribute arguments must be constants!) Luckily, MbUnit 2.4 will implicitly convert your doubles into decimals for you...

    Where credit is due: I discovered this here.

  • REMIX DAY 1

    Despite the fact that I got off to a miserable start (walking along the Charles, rain soaked and a bit lost) today was a blast.

    I got to hear Rockford Lhotka (of CSLA fame) along with Anthony Handley describe their recent experiences with WPF. This was cool because they've been working on the same kind of project as Rob and I. It was very affirming. I mean, it's kinda of like meeting a rock star and realizing that he's practicing the same guitar riffs you are. :-)

    We also attended a great session on casual game development in Silverlight by Andy Beaulieu. Andy demonstrated how to build a simple game using Visual Studio and Blend. I think that's pretty impressive for one session. I recommend checking out the examples on his site if you are interesting in Silverlight, even if that interest is unrelated to game development.

    We also caught up with fellow Floridian, Bill Reiss. Bill is an XNA MVP, who recently ported a popular physics engine from XNA to Silverlight. He has a ton of XNA tutorials on his site. I'm looking forward to pouring over some of his content.

    Finally, I want to put in a good word for the guys at eRain (I forgot to ask them their names!) They were genuinely friendly, and it really excites me to see a company like that being successful. I'm looking forward to seeing ZAM3D and Standout!

    All in all, I can't say that I learned much, but I really enjoyed meeting all these techies and sharing their passion. I was a little reluctant to post, because I don't want to seem like I'm dropping names to be cool. In the end, I decided to mention all the people that left an impression on me through out the day, not because I want to be cool, but because they are cool and it's both good and fun to get a chance to meet them.

  • My Favorite Keyboard Shortcuts

    I'm such a wannabe ReSharper padawan. My motivation is good though: I want to be more productive.  On a recent project, I was writing some code in front of a client employee, a novice developer himself, and he exclaimed "The code is just writing itself." 

    I learned a long time ago that I could impress my clients by navigating without the mouse, more recently I learned that I could get more work done without it.

    Enough talk, here is my current set of favorite keyboard shortcuts.  Some are ReSharper (R#) and some are Visual Studio (VS).

    VS Ctrl+K,C Comment out a block of code
    VS Ctrl+K,U Uncomment a block
    VS Ctrl+K,D Format your code, I prefer R#'s version but this is handy for XML.
    R# Ctrl+Shift+R Presents a context-sensitive menu for refactoring.  This is a must for newbie ReSharper padawans.
    R# Alt+Enter Another padawan must; this present recommended refactorings, e.Shiftg. inserting a namespace, changing accessibility of a member, etc.
    R# Alt+Insert The 3rd padawan must; this helps you insert "missing" code and is essential for TDD.
    R# Ctrl+Alt+Shft+F It's a handful, but it reformats your code.  This can sometimes be a bit much, and can cause some unnecessary churn in source code repository. (I do it without thinking.)
    VS/R# Ctr+Space Did you know that R# will even suggest variables names?  Isn't that totally sweet? Yes. Yes it is.
    R# F6 Moves a class, either to a new namespace or (my favorite) to a new file.
    R# Alt+F7 Find usages.
    R# Ctrl+Left Click I was giddy when I discovered this.  This is equivalent to Go To Definition.
    VS Ctrl+- That's the minus key.  It's like the back button in your browser, it takes you back to the last file you were editing.  This is incredibly useful when you are writing a test, you insert a member into the class under test, and you want to jump back to the test.  w00t!
  • REMIX07: are you going to be there?

    Rob and I are heading to the REMIX conference in Boston.  I'm really excited about the trip (I worked in Burlington, MA in 96/97 and really fell in love with the area.)  I'm hoping to pack away as much Silverlight knowledge as I possibly can while I'm there.

    If anyone else is going to be there and you'd like to hang out, drop us a line. For better or for worse, I'm always in the mood to talk about technology.

More Posts Next page »

Red-Gate!