Archive for January, 2009

We All Write Bad Code

10 commentsWritten on January 24th, 2009 by
Categories: Opinions

I recently read a post from J.P. Hamilton where he admits that he sometimes writes bad code. I quote:

That’s a brave admission in our industry, but I am willing to bet that even the best of best write bad code now and then.

I would go even further than that. Any developer who claims he never writes bad code is either lying, ignorant or living in a fantasy world. The thing is, as J.P. points out, is that good developers will try to minimize the amount of bad code that they write, and when they do, that they try to get rid of it as soon as they can. But if those developers are so good, then why do they occasionally write bad code in the first place?

Building software takes resources and requires dealing with constraints. With resources i mean more than just the number of developers that are available to work on a project. Software libraries are resources. Tools are resources. A lot of things can be resources or constraints (sometimes they can be both simultaneously). And obviously, each resource has a certain level of quality, which can have a positive or a negative effect (which enables these resources to also become constraints).

The cumulative effect of all of these resources and constraints means that you sometimes need to make compromises. One of those compromises can be that a good developer comes to the realization that for whatever reason, he (apologies to my 2 female readers: it's not easy to refer to developers in a gender-neutral way all the time ;) ) needs to write bad code to make a problem go away. Code that is not up to his usual standards and that he is not proud of.

This is usually referred to as incurring some technical debt. Nobody likes to incur debt, but sometimes you just can't avoid it. If incurring some debt enables you to start creating value sooner rather than later, then it might actually be a good idea to do so, provided that you have the means to pay back the debt later on at a reasonable cost. You definitely should strive to keep that debt as low as you can (or even eliminate it entirely) because if you don't pay off the debt, you're definitely going to regret it sooner or later.

I honestly have a lot more respect for developers who can identify the need to occasionally write a bit of bad code instead of foolishly clinging to a dogmatic "i shan't write bad code, no matter what the circumstances" stance. Well, as long as they remember to pay off their debts as much as possible, and that they do strive to write clean code as much as possible ;)

Which Path To Follow?

10 commentsWritten on January 20th, 2009 by
Categories: Opinions

Being a .NET developer isn't easy. Being a .NET developer who wants to get better all the time is even harder. Where do we go for guidance? Where do we go to get that valuable knowledge that will help us improve our skills and help us serve our customers/employers better?

A lot of .NET developers expect this kind of guidance from Microsoft, particularly from groups like Patterns & Practices. In the past, i honestly think they did a pretty lousy job at that. In the last year however, i think we've seen some positive signs that things are improving, although rather slowly.

There's also an ever increasing group of .NET developers who look to the ALT.NET community for guidance. There are a lot of talented, motivated and passionate developers in this community and there certainly is a whole lot of valuable knowledge to be found there. However, in the last couple of weeks especially, it seems like this community is ruled by the Holy Trinity Of Continuous Bitching. Well, the mailing list especially. At times it feels embarrassing to even be subscribed to it, although there still is the occasional nugget of interesting information to be found. At least, if you don't mind going through all of the high-school drama to get to that valuable information.

So who should we, the regular nobodies who happen to develop software for a living look up to for advice and guidance? Should we just listen to what Microsoft recommends? Hmm, no. Should we blindly follow the supposed ALT.NET leaders? Please don't.

Here's what i recommend: try to learn from the people who actually make sense to you. It doesn't matter who they work for, what they have done in the past, what they are working on right now, or even how unknown they are. If it makes sense, it makes sense. If it helps you improve your current way of working, it's a step up already. It really doesn't matter if what you're doing is 'right' according to the 'big shots'. Do what works for you. Do what helps you improve what you're doing. Don't resort to blindly following anyone.

I Don’t Really See The Problem With NHibernate’s XML Mapping Files

16 commentsWritten on January 18th, 2009 by
Categories: NHibernate

Fluent NHibernate is an interesting new project that allows you to configure your NHibernate mappings with a fluent API instead of using the typical XML mapping files. I think it's great that Fluent NHibernate exists, as there are quite a few people who dislike NHibernate's mapping files. But i don't really see why so many people dislike the XML mapping files.

I've stated many times before that i seriously dislike having to write a lot of XML just to get something working. Most of that comes from previously having used some of P&P's older offerings. XML can be easy to read and write or it can be very painful to read and write. I feel that a lot of Microsoft tools which can be configured with XML are typical examples of the painful kind of XML. The old "XML is like violence: if it doesn't work, apply more!"-joke certainly comes to mind here.

But NHibernate's mapping XML? I think it's pretty nice to be honest... it's not too verbose, and if you add the XSD to Visual Studio's XSD folder, the Intellisense support is pretty good. When you're starting out with NHibernate, it might take some time getting used to it, but i don't think the learning curve (for mapping) is that much higher for the XML mapping than it is for Fluent NHibernate.

A lot of people also say that better refactoring support is a great reason to move to the Fluent NHibernate... that's true but there's also a Resharper plugin which supports refactoring NHibernate mapping files.

One reason to stick with the XML mapping files for now is that Fluent NHibernate doesn't have support (yet) for everything that the XML mapping files allow. This is probably only a temporary issue as Fluent NHibernate seems to be under pretty active development. But if you run into something that isn't supported yet by Fluent NHibernate, yet is supported by the XML mapping files then you might end up with 2 sources of mapping: most of it in code, and some of it in the XML files. I'd prefer to have all of the mappings in one format/style so that might be an issue until Fluent NHibernate supports everything the NHibernate XML mapping files do.

This is certainly not meant to dissuade people from using Fluent NHibernate. I just prefer to use the XML mapping (for now) and since nobody seems to be sticking up for the XML mapping, i figured i'd stand up :)

How about you guys? Do the mapping files really bother you? Or do you prefer the XML over Fluent NHibernate?

Design Principles That You Should Try To Stick To

No Comments »Written on January 18th, 2009 by
Categories: Software Development

Writing a post about some of the most important design principles has been on my TODO list for a long while now. And luckily, Laila beat me to it :)

Abstracting Request State

22 commentsWritten on January 17th, 2009 by
Categories: ASP.NET, WCF

Sometimes it's useful to be able to store an object somewhere so you can easily access it for the duration of the current request, instead of having to pass it around with every method call that you make. That request could be an ASP.NET request, or a request in your WCF service layer. I used to resort to storing these objects in ThreadStatic fields (which is basically a static reference for each thread), thinking that it would be safe because only one thread handles a complete request. Last week i read that some requests can be paused and resumed by another thread. If you're using ThreadStatic fields, this could lead so major issues which would be a royal pain in the ass to debug. In order to prevent this possible problem, i wanted to have a safe way to keep state that should be available for the duration of a single request.

If your code executes in an ASP.NET environment, you can safely use the HttpContext.Current.Items dictionary for this. If your code executes in a WCF environment, you can store these things in the OperationContext. I don't want my code to be tightly coupled to either ASP.NET or WCF, so i wanted some kind of abstraction. This is the approach that i came up with.

First, we have the IRequestState interface:

    public interface IRequestState
    {
        T Get<T>(string key);
        void Store(string key, object something);
    }

This just offers a way to store objects and retrieve them. That's pretty much al we need, right?

Then we have the ASP.NET implementation:

    public class AspNetRequestState : IRequestState
    {
        public T Get<T>(string key)
        {
            return (T)HttpContext.Current.Items[key];
        }
 
        public void Store(string key, object something)
        {
            HttpContext.Current.Items[key] = something;
        }
    }

Very simple stuff... the AspNetRequestState implementation simply uses the HttpContext.Current.Items dictionary underneath to store and retrieve the objects.

For WCF, it is slightly more complicated. Every WCF call is an operation and it has a context as well, which is provided through the OperationContext class. The OperationContext class doesn't have an Items dictionary like HttpContext does, but it does have a way to add extensions to the context. We can use this extensions mechanism to store state which should be kept around for the duration of the current WCF operation. First, we need to define our Extension:

    public class MyExtension : IExtension<OperationContext>
    {
        public MyExtension()
        {
            State = new Dictionary<string, object>();
        }
 
        public IDictionary<string, object> State { get; private set; }
 
        // we don't really need implementations for these methods in this case
        public void Attach(OperationContext owner) { }
        public void Detach(OperationContext owner) { }
    }

The IExtension interface that we must implement defines the Attach and Detach methods but we don't really need them for what we're trying to do. This extension simply initializes a Dictionary instance and exposes it with a public getter. Now we can easily create our WcfRequestState implementation:

    public class WcfRequestState : IRequestState
    {
        private static IDictionary<string, object> State
        {
            get
            {
                var extension = OperationContext.Current.Extensions.Find<StateExtension>();
 
                if (extension == null)
                {
                    extension = new StateExtension();
                    OperationContext.Current.Extensions.Add(extension);
                }
 
                return extension.State;
            }
        }
 
        public T Get<T>(string key)
        {
            if (State.ContainsKey(key))
            {
                return (T)State[key];
            }
 
            return default(T);
        }
 
        public void Store(string key, object something)
        {
            State[key] = something;
        }
    }

Pretty simple as well, and pretty similar to the AspNetRequestState implementation. The AspNetRequestState implementation is able to simply use the HttpContext.Current.Items dictionary, which we can't use here. So when we want to access the 'State' dictionary in this implementation, we look it up in the current OperationContext's Extensions collection. If it's not there yet, we add a new instance of our MyExtension class to the OperationContext's Extensions collection.

Now we can use this wherever we need to store something for the duration of the current request, regardless of whether we're executing in an ASP.NET or WCF context. Just configure your IoC container to create instances of AspNetRequestState whenever an IRequestState instance is needed in your WebApplication, or configure it to return WcfRequestState instances in your WCF service. The code that needs to store some request state will no longer have to resort to using ThreadStatic fields, and it doesn't need to know about it's runtime environment either. It merely needs an instance of IRequestState.