AJ's blog

August 31, 2009

PDC08 – the unrevealed crime (Part 1)

Filed under: Fun — ajdotnet @ 6:20 pm

Alright, this blog is hijacked! I’m not going to tell you who I am, and it’s up to you whether you believe me or not. But I’m here to tell you the truth! The truth about what happened last PDC. I have to be careful, though. Once the word gets around, I will be in grave danger. Thus I have to keep my anonymity. Nobody will be happy about me telling the world about… THE CRIME.

You never heard about it? No wonder. Ask someone who was at the last PDC to tell you something about THE CRIME. You’ll see people hunching down, backing off, finding excuses to leave, or otherwise evading the topic. It’s the dirty secret we all share and that to the best of my knowledge, nobody has told yet. It’s a hideous crime, and the cove-up that ensued is on par with the fake moon landing. (You know the moon landing never happened, don’t you?)

But this time, it’s going to be different. This time the truth will be told. I will tell it, for I cannot bear the burden of endangering the attendees of the upcoming PDC on my conscience.


It happened to the most revered, and well regarded, father of Turbo Pascal. (And some other languages, I guess. He never managed Modula, though, but that’s really NOT AN EXCUSE!): Anders Hejlsberg!


I was a witness and I happened to have my camera ready to document THE CRIME first-hand (and I sneaked it out when all cameras where confiscated!). See for yourself:

 “What’s that…?” “No… that can’t be…? Must be some hardware problem…”

 “Really it has to do with these cables…?”
“No Anders, look at your screen. If the problem is not on the screen, it’s probably in front of it.”


Note: In the interest of the innocent I’ll leave out the rather pitiful scenes and groundless accusations that followed. Suffice it to say that Anders eventually had to accept the fact that somebody installed LINUX on his machine! Imagine the insolence! The effrontery! the sheer impudence! A penguin mocking a distinguished person like Anders, and along with him the whole assembled Microsoft celebrity!

Of course that didn’t amuse Anders in the slightest way…


 “I’m usually a nice and likable guy, …”

 “… but let me get my hands on this culprit, this evildoer, this…” (again, I have to protect the innocent.)


And yet, this… abomination… was only the beginning of the story…. But I have to go, that guy over there is eying me suspiciously. More when I’m save again…


August 30, 2009

Silverlight Bits&Pieces – Part 5: Service Call Basics

Note: This is part of a series, you can find the related posts here

This time, building on the last post, I’m going over the basics of getting data to the client. The order of the day is just get it working, I’ll come back later to address some issues.

The Service

I have to provide the service first. This is easiest done by adding a Silverlight-enabled WCF service, located in the “Create New Item” dialog, under the Silverlight group. It comes with the necessary configuration, ready to use. After defining the EF model, a first service operation delivering recently acquired books may look like this:

Note the Sleep. I like to stress the asynchronous nature of the SL client and I want the client code to handle this properly, thus the Sleep makes the time lag very apparent.

Note: This way I know very early where I should provide visual feedback, or disable controls. This is especially important considering that on my development machine I will hardly spot any delay, but once the application goes into production and network performance and latency demand their toll, this will likely change.
Thus I recommend you do the same, perhaps surrounding with #if DEBUG and making it configurable.

Calling a service

After running the web application, Cassini provided a live version, which I needed to create the client side proxy. This generates respective code, of course including the data defined in the contract. Those classes already (by default) implement INotifyPropertyChanged and use ObservableCollection<T>. It certainly will give you a head start if you can use these classes as your model.

For every service operation there is a respective MyOperationAsync() method that initiates the asynchronous call and a MyOperationCompleted event that delivers the result. (No synchronous version by design!)

One hint: Creating the client proxy also created a ServiceReferences.ClientConfig file in the service assembly. This file is needed in the UI project to be available for the client. It works quite well to include it in the UI project be setting a reference, rather than just copying the file (“add existing item”, “add as link”), and this way you won’t have to keep a copy in sync.

Wiring it Together

The idiom is documented well enough, thus without further ado, my first version looks like this:

The client instance is also used to detect whether the last call is still under way, and to suppress further calls.

The UI includes a button to trigger the server call (just for now, in this case the call will eventually be made from the c’tor), and the DataGrid to present the result:

The respective event handler is trivial as well:

Now, running the app looks like this:

Clicking the button… waiting… that’s why I put the Sleep in… . Oh, and I can click the button as I like? … Finally the result appears:

Regarding the “I can still click the button…”, I wanted to make this point specifically, because I have already seen people ignore that time lag too easily. It no only makes your application “feel unresponsive” in case of longer operations, because the user doesn’t get any indication whether the application has actually accepted his button click. It also may makes your logic more complex if it had to deal with multiple calls at the same time. My code simply ignored them, but there is no reason why they shouldn’t be processed as they come in. Even canceling the previous call may make sense, because it may be obsolete due to changed parameters (most operations are certainly not as simple as the one used in this example). You may want to cancel if the criteria actually changed and ignore the subsequent call if the criteria stayed the same… . See? Quickly the complexity adds up. The easy way around is disabling the button and making the user experience a sequential one.

Providing visual feedback

So, the logical step is to add a respective property CanLoadBooks and use it for the binding…

After that, disabling the button can be done via data binding the IsEnabled property:

And nicely my application provides visual feedback and at the same time prevents the user from redoing what he did:

The stage…

This post sort of completes the initial setup of the stage for my Silverlight application. I have a solution, the basic layout is in place, the general application architecture and data binding strategy is set up, and with this post I can talk to the server.
From here I will go exploring various aspects, probably at random, but now I have the means to do so.
And there is a lot of aspects to cover anyway. The services part I addressed in this post is by no means covered exhaustively, neither is data binding. Other topics haven’t yet been mentioned at all, like basic application services, visual state manager, navigation, or configuration.

Anyway, I will have to work on it before I can write about it. So this series is certainly not coming to an end, however further posts may take some more time. And I have a small by-project running, some mischief I’m up too 😉

That’s all for now folks,

kick it on DotNetKicks.com

August 27, 2009

Silverlight Bits&Pieces – Part 4: View Model Basics

Filed under: .NET, .NET Framework, C#, Design Time, Silverlight, Software Development — ajdotnet @ 8:48 pm

Note: This is part of a series, you can find the related posts here

Displaying and manipulating data on the client – the one and only purpose of any LOB application – includes two things if it comes to Silverlight: a) The asynchronous server calls and b) the client architecture. I will be going over them in a cursory fashion and come back later to address each one in more depth. This time the client architecture.

View Model basics

The client code is largely guided by the employment of the Model-View-ViewModel (M-V-VM, or MVVM) approach, which is the predominant architectural approach used with SL and WPF. The reason probably being that it is a natural counterpart to the WPF and Silverlight data binding features, the two work extremely well together.

Cook book style:

  • For every page (the view) there is a respective class (the view model) that manages the data (the model).
  • For each control on the view that shall be populated dynamically with data, the view model has a corresponding property providing the model.
  • For each control state, such as enabled or visible, that shall be controlled by the logic, the view model has a corresponding property, probably boolean.
  • For each action triggered by the UI the view model has a respective method.

The view model is very closely associated with its view, so there is not much reuse here, but then, it largely consists of properties and forwards to service calls. Or so the theory says. (Subsequent posts will gave deal with the shortcomings….)

Please note that it is debatable whether the data provided by the view model actually is the model. Another approach would be to expose a view related data model, namely view entities. The view model would have to map them to the data model (the model) the lower layer exposes, probably some service proxy.

Both approaches have pros and cons, however you’ll mostly see the former approach, since it’s well supported by the tools (service proxy generation, etc.). Still, it has some cons…

Anyway, the only technical demand for view models in SL is due to the intended use for data binding: Classes subject to fully fledged data binding need to support the INotifyPropertyChanged interface for simple properties, while collections have to support INotifyCollectionChanged. The later one comes for free if you use ObservableCollection<T> consequently. (Please note that data binding works with conventional properties, but only to a limited degree.)

For INotifyPropertyChanged a little base class comes in handy:

Note the generic overload. That’s a little trick to avoid typos in the property name argument.

With this class as base a property implementation usually follows this idiom:

(Without that trick one would have to pass the property name as string. A source of errors due to typos, and a pitfall during refactoring.) 

BookFilter is a data class that, again, follows the same pattern, i.e. it supports INotifyPropertyChanged.

Hint: This begs for a code snippet! 🙂

The View Model

Any book shelf has a collection of books, so does my application. The book list page should provide a means to filter the book list (two text boxes), a button to trigger the search, and to show the result (a data grid):

Not especially nice and the grid is a little degenerated for now, but that will change. In XAML:

Thus the first view model implementation may look like this (including some simple test data, the next post will deal with the server call):


For the actual binding I need to wire that up with the page. The usually presented manual way looks like this:

The view model class is created in the c’tor, and assigned to the DataContext. A property provides a more convenient access to it. This is already used in the button event handler that triggers the book search.
However, I recommend against this way. Rather I did the data binding in Blend…

Opening the page, selecting the first textbox, finding the Text property in the properties and clicking the text box (or that tiny little dot to the right) brings up the context menu.

Then I choose data binding, the Data Field tab, and the +CLR Object button:

That left finding the view model class and selecting it:

This way I could add various “data sources”, yet I only want one for now, and according to M-V-VM, for ever. Afterwards the dialog lets me browse the class structure and select the property to bind against:

On second thought, I selected the StackPanel which contains the filter textboxes and bound it against the BookFilter property, in order to narrow the available context. Afterwards the textboxes could be bound via the Explicit Data Context tab:

I had to expand the lower area to set the binding to TwoWay.

But I didn’t have to go through the dialog armada for every field. Blend also provides the data tab that lets me browse through the available data sources. Drag’n’drop of field simply works and generally uses the last settings from the dialog, i.e. it includes the TwoWay setting. Also it binds by against the default property, but if I hold the shift key down it lets me choose the property. And some other stuff I leave to you to explore. Really nice.

Anyway, this is what Blend just created for us in markup speak (just the relevant part):

It registered the namespace to locate the view model class, created the view model as resource, set the DataContext of the LayoutRoot element to this resource, and it added the usual binding to the subsequent controls.

Changing the generated prefix to viewModel was all I did. Otherwise I could live very well with that, given that is achieves all I need and it allows me to do my data binding much more efficient and less error prone in Blend. The manual way was opaque to Blend, thus it couldn’t assist me in any way.

The only thing left was removing the manual instantiation from the c’tor and changing the ViewModel property to use the LayoutRoot control. I may have moved the binding to the page instead, but I prefer to work with the tools, not against them.

After running the application and clicking on the button, it shows the respective test data:

The next post will deal with the actual server call.

That’s all for now folks,

kick it on DotNetKicks.com

August 21, 2009

Silverlight Bits&Pieces – Part 3: First Layout

Filed under: .NET, .NET Framework, Design Time, Silverlight, Software Development — ajdotnet @ 9:48 pm

Note: This is part of a series, you can find the related posts here

One thing is as true with SL as it was with HTML and CSS: Starting with a basic layout of the pages and a “site map” really helps a lot. (Trying to work with a style system that you don’t know doesn’t.)

The application created by the template looks like this:

It’s a navigation application with head area (including menu) and remaining work area. It uses a Grid control, yet only as kind of canvas, all controls are placed via margins and alignments. I find this, well, curious, there is a canvas control after all. But the layout doesn’t suit me anyway.

So the first step is to get rid of all styles, i.e. I cleaned Assets/Styles.xaml. That included removing all references to these styles, as in this fragment:

Searching with a little regular expression solves that problem. Now for the intended layout:

I want to have a head area with application title and other information. A left area containing the menu. A bottom line with legal information. And finally the remaining area for our pages. And some space between for some visual separation.

In SL this is done with a Grid. Curiously enough, for this is akin to table layout in HTML. I wonder when the CSS gang will show up and cry wolf 😉

Most samples show and explain how to write the markup to define rows and columns. But then, most samples are pre-created and reiterated, and I have problems “mind rendering” the markup. With the Silverlight 2 SDK there was at least a kind of preview in VS, but with SL3 that preview does not work (the document outline may help to navigate larger XAML files, though):

So I chose a different way and put Blend to its first use…

Grid layout

Defining the desired Grid layout can be done easily in Blend. Placing rows and columns is just a mouse click away: Clicking on the areas to the left or the top adds new rows and columns. Clicking on the symbols changes the type. If you don’t see them, change the layout mode by clicking in the upper left icon.


Once the rough layout is done, it can be saved and one can switch back to VS. The resulting markup is very clean, Blend generally does a good job producing clean markup and at the same time leaving your markup as it was.

Placing the contents

Next step was creating controls for the three areas (head, menu, footer) and move the respective content from the page there (copy & paste in VS). The markup now only contains the navigation frame, which is the working area. Drag & drop and some more mouse jostling in Blend positions that control in the correct cell:

And sizing it correctly:

Also – after recompiling the solution – Blend picked up the user controls and offered them as assets if you select Project. Again some mouse jostling later (and with different backgrounds colors for each user control to distinguish them) the result looks like this:

Blend automatically generated a namespace definition as prefix for the controls, using a veeerrrryyyy long prefix name. But that’s easy to solve and to replace with control. The final markup is, again, very clean:

After some working on the user controls and some styling… alright, it may take some time, but had it ready from some internal application, and besides it was done by a colleague, for if I had done it myself if would probably cause eye cataracts… , the end result looks like this:

This may all seem trivial if you’ve been through this experience once. Bottom line I guess is the way I worked through this (which may or may not work for you). It’s the combination of VS and Blend, working with both tools at the same time. Even if you are a markup guy rather than design time worker in ASP.NET, my recommendation is that you give Blend a chance. It’s far more stable than the ASP.NET designer in VS ever was. I’m not saying you should switch to Blend, just get the best of both, VS and Blend.

The next post will contain some real code, promise 😉

That’s all for now folks,

kick it on DotNetKicks.com

August 19, 2009

Silverlight Bits&Pieces – Part 2: Silverlight Solution

Note: This is part of a series…. Well, it will be ;-) 
You can find the related posts here

Alright, let’s start looking into some Silverlight 3 (SL3) development. Specifically of business applications.

First step is a respective solution. I created a new “Silverlight Navigation Application”, with SL hosted in a web site, and got the typical solution structure. Needless to say, that this structure doesn’t meet my requirements.

First, I’m going to have a bunch more assemblies. And since SL assemblies are different from “ordinary” assemblies – they work against a different runtime and use different libraries – I like to have them clearly distinguishable. I did this a) with respective solution folders and b) with an added namespace part “SL3”.

The Server Part

On the server side I added two assemblies:

One data access assembly. This contains the ADO.NET Entity Framework access to the database. For the purpose of this application, this constitutes the business layer. (A little simplistic, but bear with me, the focus is on the client.)

A “Common” assembly. There will be server side parts of logic that may be reused in other applications.

I also made some adjustments to the web application (project properties/web): I changed virtual path to “/xBookshelf”, I don’t like my web apps to occupy the root. And I set the port to “specific port”. It doesn’t matter which one, it’s just a little annoying to have to update service references when the port is changed by VS every now and then. Speaking of services, I’m going to put them in a separate folder.

The Client Part

My naming convention for SL3 assemblies is Company.Application.SL3 . Specifically I renamed the SL assembly containing the XAML files to SDX.Bookshelf.SL3.UI. Renaming the .xap file affects the web project and the hosting pages. I also changed the pages to have Page as postfix.

And there are a few additional assemblies as well:

SDX.Bookshelf.SL3.Model contains the view models, as I’m going to use the Model-View-ViewModel pattern.

SDX.Bookshelf.SL3.Service contains all service references. Since this is all generated code, I thought it prudent to cleanly separate it.

SDX.SL3.Common is the counterpart to the server side common assembly. It will contain everything that may be reused in other application.

Setting the project dependencies and getting it all to run again is just a bit tedious, especially because the startup project is the web project, but the application in question is the UI project.


The final test for the reworked solution is opening it in Blend – which may be not as trivial as it sounds 😦

You will at least get one warning dialog telling you that blend does not support solution folders. Never mind, that’s of no consequence.

In one project I also run into a serious issue: Blend refused to open the solution with the following dialog:

Also subsequently I got a large message box with an exception stack trace.

To work around this problem, I removed all projects from the solution and added them again in Blend. I was able to provoke that bug by reordering the sequence of the projects within the .sln file, hence it’s probably due to some project dependencies that blend can’t solve correctly.

Anyway, don’t let that bias your perception. Blend may be awkward, and it takes time getting used to – but is worth the effort.

That’s all for now,

kick it on DotNetKicks.com

August 17, 2009

Silverlight Bits&Pieces – Part 1: Introduction

With Silverlight I was lucky…

  • I never got to look into Silverlight 1, so I avoided the scripting mess 😉
  • For Silverlight 2 I participated in some research efforts on our company and I worked on a business solution (as in business solution, not just a “simple” control). This did not only include the obvious stuff like drawing and driving the UI, but also some necessary groundwork.
  • Microsoft launched Silverlight 3 officially on Friday, July, 10th; on the following Monday, July, 13th, I was officially in a customer’s Silverlight 3 project. We had just waited for the availability 😉

And to relay the probably most important experience for me so far: Working with Silverlight 3 and Blend is fun!

It’s easier to get what you want than with web applications, the programming model is much more concise and powerful than ASP.NET, Blend has a far better user experience than the WebForms designers ever had (after being nearly a decade and several versions old!).
For me, working with Silverlight has a thrill factor comparable to what I encountered when I first started to develop with .NET.

Note: From now on, I’ll refer to Silverlight 3 simply as SL.

So, I may have a little head start with SL business applications and their demands, but I’m sure that will wear down over time. Anyway, I thought I might share some of the experiences, insights, and ways I discovered.

This is not going to be me providing a tutorial, or me telling you what to do. It’s about me telling you what worked for me. Some may be outright trivial (especially the first ones, laying the foundation), some may be about the how to do it, rather than the what to do. But then, I also had to tackle a few things that go beyond the usual “My first Silverlight Hello World Application” type of samples.

Disclaimer: This is as much about telling you how I did things as it is a learning experience for me. I may be wrong at times. I may tell you in one post to go left and a few posts later that you had better not listened. No warranties here, sorry.

And I’ll try something different and keep the posts short and to a certain point 😉 (and I admit that this post is already in violation with this intention…).


Just for the record: I’ll base the work on SL as you can get it here. That includes:

  • Microsoft Silverlight Tools for Visual Studio 2008 (includes developer runtime and SDK)
  • Microsoft Expression Blend 3 + Sketchflow

I refrained from using RIA services, because I want to understand the technology bare boned. That being said, I think that RIA services has really great potential and for those interested I recommend Brad’s series. I also haven’t thought about including the control toolkit, yet.

Setting the stage

My way of learning a new technology is usually a) read about it to understand the idea behind it, b) do some technical prototypes to dive into one or the other feature, and c) take a real world example and see how the technology fares. In my experience, point c is the most important, because it goes beyond the usual samples that are built to suit the technology. Rather it stresses the technology’s abilities to meet actual needs. This is usually when you’ll encounter the pitfalls.

My real world example for SL was kind of a library or book management application. At SDX we maintain our books in a simple SharePoint list, so every colleague knows what books are actually available, where to find them, who has borrowed it currently. This list is more intended to keep people informed, than controlling whether they return the books on time. Weren’t our colleagues dispersed at various customers’ sites, a simple bookshelf with no bureaucracy at all would be sufficient. (And I wouldn’t have to go hunting for lost books every now and then 😉 .)

The Database

The database I’m going to use is simple enough. It contains books, information about who borrowed it, and user information:


Additionally I like to create views as I need them (rather than using EF for this). For example BookInventory contains all books as well as the related information on the currently borrowed books and employees.

And with these conditions set, we are ready to start. The next post will start at the beginning, stay tuned 😉

That’s all for now folks,


August 3, 2009

Der Lügen-Limbo der Ursula von der Leyen [MOVED]

Filed under: Miscellaneous — ajdotnet @ 8:32 pm

Moved: http://alexanderj.wordpress.com/2009/08/03/der-luegen-limbo-der-ursula-von-der-leyen/

August 1, 2009

Posting Guards: Guard Classes explained

Filed under: .NET, .NET Framework, C#, Software Developers, Software Development — ajdotnet @ 11:53 am

A colleague writing an article about code contracts recently asked me about some useful links about Guard classes, something I have been advertising for some time. ‘Sure’, I thought — and was taught otherwise.

There are certainly references to Guard classes. For example this one hinting at an implementation from MS Patterns&Practices, although an outdated one and no online documentation available. And this one talking about using Guard classes in combination with LINQ.

Still, nothing explaining the concept, nothing on Wikipedia, nothing anywhere. Can it be that Guard classes are far too simple to be worth mentioning? I don’t think so, because while the implementation certainly is simple, I wouldn’t have had to explain the concept that often if that where the reason.

So, what are Guard classes?

First of all, let’s make sure we’re taking about the same thing. Judging from the name, Guard classes are about guarding against something, but this can mean just about anything. Actually I found two incarnations: One, guarding against concurrent access, i.e. some kind of locks. And two, guarding against the passing of invalid parameters into a method – which is what this post is about. (You may have come across Guard classes by the name of ArgChecker, ArgumentHelper, or something similar, or as single helper methods appearing where they don’t belong.)

Straight to the matter: Have a look at the following example:

IEnumerable<Employee> FindCustomers1(Guid companyID, EmployeeFilter filter)
    IEnumerable<Employee> result= null;
    if (companyID!=Guid.Empty) // only hit DB if we have to
        using (DatabaseDataContext context = new DatabaseDataContext())
            result = from e in context.Employees
                         where e.FirstName == filter.FirstName && e.LastName == filter.LastName
                         select e;
    return result;

While probably doing its job properly, this method isn’t exactly defensive. The issue should be apparent: What happens if the caller passed null for the filter? Not that he is expected to, quite the opposite, but anyway?

You could try to handle that in code and it would probably lead to some ugly code, as Abby rightly complained about. And to be blunt, that approach is wrong right from the start. If caller is not supposed to pass null values into our method, why should we clutter our code with conditions that aren’t supposed to happen anyway.

The better solution is getting rid of unwanted null values by making them illegal. And not only by politely asking in the documentation (and please RTFM); rather make it unmistakably apparent, punish any violation, make it impossible to bypass. In other words, check the parameter and throw an ArgumentException.

On second thought, the same reasoning applies also to the properties of our filter object, so we may end up writing the following code, prone to becomes ugly itself:

if (filter == null)
    throw new ArgumentNullException(„filter“);
if (filter.FirstName == null)
    throw new ArgumentNullException(„filter.FirstName“);
if (filter.LastName == null)
    throw new ArgumentNullException(„filter.LastName“);

And we actually did expect some content, so why not go ahead and do some other vanity checks:

if (filter.FirstName == „“)
    throw new ArgumentNullException(„filter.FirstName“);
if (filter.LastName == „“)
    throw new ArgumentNullException(„filter.LastName“);

But wait. An empty string is certainly not null. Unfortunately there is no StringEmptyArgumentException. Should we use an ArgumentOutOfRangeException? Or an InvalidOperationException, not an ArgumentException at all? Derive a new one? ArgumentOutOfRangeException may look nicely to me, but my team mate just settled with ArgumentNullException, which is at the least an inconsistency… .

And what the heck, this is way too much code for nothing anyway. And so we end up not checking our parameters and hoping for the best…?

Now consider this code:

IEnumerable<Employee> FindCustomers2(Guid companyID, EmployeeFilter filter)
    Guard.AssertNotNull(filter, „filter“);
    Guard.AssertNotEmpty(filter.FirstName, „filter.FirstName“);
    Guard.AssertNotEmpty(filter.LastName, „filter.LastName“);
    IEnumerable<Employee> result = null;
    if (companyID != Guid.Empty) // only hit DB if we have to
        using (DatabaseDataContext context = new DatabaseDataContext())
            result = from e in context.Employees
                         where e.FirstName == filter.FirstName && e.LastName == filter.LastName
                         select e;
    return result;

We just replaced 5 ugly conditions (10 LOC) with 3 calls. Let me rephrase that: We replaced a bunch of code detailing some implementation with 3 lines revealing the intention – way more readable. Wow! By centralizing the checks, we were able to provide more convenience (putting the null and string empty check in one method), we ensured consistent behavior, we improved the calling code considerably. And finally, we even added some more information to the exception, as you will see in the implementation:

static public void AssertNotEmpty(string arg, string paramName)
    if (arg == null)
        throw new ArgumentNullException(paramName,
            „Argument ‚“ + (paramName ?? „<missing>“) + „‘ should not be NULL!“);

    if (arg.Length == 0)
        throw new ArgumentOutOfRangeException(paramName, arg,
            „Argument ‚“ + (paramName ?? „<missing>“) + „‘ should not be empty!“);

You don’t want to put that code in every method. But you do want to call the Guard method, don’t you?

Now that we have established what Guard classes are, let’s look at …

What are Guard classes about?

So far I introduced Guard classes form the coding level, merely as convenient helper classes. But there’s some broader meaning to them, namely in the following areas:

  • Contracting
  • Self preservation
  • Robustness


Contracting as a means has gained attention as important aspect of SOA service design, and also as development approach, namely design by contract. Contracting may be a major undertaking if it comes to SOA services, yet it can also be employed on a much lower level, designing the public interface of a class.

A little simplified, a contract of a class or service consists of

  • Functional contract: Specifies the operations, the semantics, required call sequences, runtime behavior, error conditions and behavior. Some of this may be expressed using code, some may not.
  • Data contract: Details parameters and return values, in other words the data that is exchanged during the operations. It defines the legal shape and values of the data, restricting it first by data types, secondly by additional demands, such as stating which parameter is mandatory, which content is required, and which values it is limited to beyond what the data type mandates. Also interdependencies between fields, and so on.
  • Some other aspects, but that’s not relevant right now.

As you see, the data contract goes beyond what the type system is capable to enforce. And Guard classes may serve as a means to express some of those aspects in code. Thus, Guard classes serve to enforce the contract of a class. And since these calls are that obvious, the code is self-documenting its preconditions quite nicely.

Note 1: Of course this makes only sense with regard to the technical contract that has to be met by the calling code, i.e. the developer, not a business contact that has to be met by the user. See my post on error handling and responsibilities for more on that topic.

Note 2: In terms of design by contract, Guard classes express the preconditions of an operation, something that has been baked into other programming languages right from the start.

Self preservation.

If you are working in a team, you inadvertedly have to work with other team members. Good ones, bad ones. And you may want to protect yourself against the later… .

Face it: If a NullReferenceException arises, the developer who wrote that particular code fragment – mayhap you – is held responsible (shot on first sight, so to speak). Even if it turned out later that the calling code passed some illegal null value… . Well, problem solved, but the stigma sticks, and anyone will only remember that the exception was thrown in your code.

How do you protect yourself against that? Guard classes. If the calling code just passed some crap data – despite you having told that guy what to pass a hundred times – just throw it right back into his face. That’s what ArgumentExceptions are for: complaining loud and clear about someone unduly misusing your code. Be the accusator, not the accused!

BTW: If you’re on the callers side and the method you just called returned a value, you may achieve something similar with Debug.Assert.

For example if you had written that code above, and I knew you to be a sloppy developer, I would certainly check the return value. And if I were as mean as you are sloppy, I would deliberately call it passing Guid.Empty as companyID. And if you dared to hand back that pesky null instead of an empty enumeration I would … .

Well, never mind. You‘re not sloppy, I‘m not mean, and I only put that bug in to stress the fact that Guard classes only work up the call chain, not down. (And yes, it’s a bug to return null in the above case. Methods supposed to be used in a LINQ context have to comply with LINQ demands, which are based on functional programming, which boils down to „no nulls please!“)

Robustness (or: making errors apparent).

Someone passed null or some other unwanted value to a method. There are actually two bad things that might happen:

  1. The application may crash further down.
  2. The wrong value may affect some data, but the application continues to work.

Number one may be bad, but at least the application crashes (which is a good thing!). Still, in this case Guard classes will help you identify the error far earlier, possibly avoiding a situation where you’ll have to hunt for the root cause of a problem. This should at least help diagnosing the problem.

Number two is far worse. It’s actually the very situation that you would want to avoid at any cost: A bug that stays unnoticed. A bug that occasionally produces wrong data, and that lingers around long enough to seriously affect data consistency to a degree that renders all data useless, because you have no way of knowing which data was affected and which not. Technically just a tiny slip, but in the long run these bugs are the most harmful.

To guard against these bugs Guard classes put up another safety net. Make sure the data coming in matches the specification.

Essentially both issues neatly demonstrate what „fail early, fails fast“ is about. Making errors apparent, prevent them from being obscured and from causing damage further down the line.

And that’s it…

Quite some task for a tiny little helper – but really worth the effort. Should you need some kick-start to employ this concept yourself, I posted the code for a Guard class here. Use it, enhance it, employ it to make you life easier.


That’s all for now folks,

kick it on DotNetKicks.com

Blog at WordPress.com.