The try-catch-return-false-throw-catch-return-false-throw-fail anti-pattern

I recently came across a wonderful anti-pattern. Well, anti-patterns are not wonderful, but the mind just boggles at the sheer bloody lunacy of this particular anti-pattern. I’m not going to show you the original code, but I’ll show a general representation of what it did:

        private void DoStuff()
        {
            if (!C())
                throw new Exception("The widget failed to process");
        }

        private bool C()
        {
            try
            {
                B();
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

        private void B()
        {
            bool worked = A();
            if (!worked)                throw new Exception("The process failed");
        }

        private bool A()
        {
            try
            {
                // Do stuff that might fail.
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }

Now I’ve not shown all the code in order to concentrate on the weird stuff. For context DoStuff() was called from the code behind file for an ASPX page, so when it throws an exception the user will be redirected to the error page. The original exception (caught in method A()) is thrown by code from within the .NET Framework itself. It is a valid exception as the situation should only ever occur if the server is misconfigured.

There are many things wrong with this, not least is the number of things thrown. Mostly, what got me was that the wonderful diagnostic information in exceptions is repeatedly thrown away. Nothing is logged anywhere, so no one would be able to ever tell what went wrong. This is utterly hellish from a debugging point of view. In this case it was because of a misconfigured server and took several hours to track down. Had the original exception been allowed to bubble to the top (with appropriate finally blocks in place for clean up) and the exception information logged then the error could have been tracked and fixed in a matter of minutes. Luckily this happened on a dev system. I’m sure a customer would not have been pleased if their revenue generating website was brought down for hours because of a minor, but incorrect, change in a web.config file. In fact, in a production environment the tools for tracking down the error would most unlikely not exist at all. On a dev system at least a debugger and easy access to source code is present.

So, how could this code have been better written?

        private void DoStuff()
        {
            try
            {
                C();
            }
            catch (Exception ex)
            {
                // If you can add information for diagnostic purposes
                // then create a new exception and throw it. Remember to
                // add the existing exception in as the innerException.
                throw new Exception("The widget failed to process", ex);
            }
        }

        private void C()
        {
            try
            {
                B();
            }
            // Do not catch the exception, nothing was was done with it.
            finally
            {
                // Do any cleanup.
            }
        }

        private void B()
        {
            try
            {
                A();
            }
            catch (Exception ex)
            {
                // Put this caught exception into the new exception
                // in order to keep the detail. This new exception
                // adds detail to the error.
                throw new Exception("The process failed", ex);
            }
            finally
            {
                // Do cleanup
            }
        }

        private void A()
        {
            try
            {
                // Do stuff that might fail.
            }
            finally
            {
                // Do cleanup
            }
        }

This is better, if you ignore the fact that I’m catching and throwing general Exception objects – You should always throw and catch the most specific exceptions that you can.

The main benefit here is that the original exception is allowed to bubble up. When it is possible to add value to the exception a new exception is created and it holds the original as the innerException object.

Note that “The process failed” and “The widget failed to process” are stand-ins to represent meaningful and valuable exception messages. In normal circumstances messages like that do not usually add value.

Mixins in .NET (again)

A while ago I wrote about Mixins in C# 3.0, at the time I was saying that you can get some of the functionality, but not all, from some of the new language features in C#3.0. The solution is a bit of a fudge because the language doesn’t support the concept. I’ve been looking at Oxygene recently and it has some language features that go a bit further than C# does and will support greater mixin-like functionality which it calls interface delegation.

Interface delegation is again a bit of a fudge, but not quite like C#. In this case the language supports this mixin-like functionality and the fudge happens in the compiler. Let’s take the class hierarchy that I used the last time:

Class-Diagram-2

In Oxygene the Dog class looks like this:

interface

type
  Dog = public class(Mammal, IRun, ISwim)
  private
      runInterfaceDelegate : RunMixin; implements IRun;
      swimInterfaceDelegate : SwimMixin; implements ISwim;
  protected
  public
  end;

implementation

end.

From this we can see that Dog inherits from Mammal and implements IRun and ISwim. The IRun interface has one method (Run), and the ISwim interface has only one method also (Swim). Of course, there could be as many methods and properties as you like.

The C# version of the Dog class, as produced by Reflector, looks like this:

public class Dog : Mammal, IRun, ISwim
{
    // Fields
    private RunMixin runInterfaceDelegate;
    private SwimMixin swimInterfaceDelegate;

    // Methods
    void IRun.Run()
    {
        this.runInterfaceDelegate.Run();
    }

    void ISwim.Swim()
    {
        this.swimInterfaceDelegate.Swim();
    }
}

As you can see, there are two private fields holding a reference to the appropriate mixin, in each of the methods the responsibility for carrying out the action is delegated to the appropriate surrogate mixin object.

What you will also notice is that you still have to instantiate the surrogate mixin objects. Under normal circumstances that would be in the constructor. If it were a real mixin you wouldn’t have the option as the mixin would be created at the same time as the object it is used with. In fact, the mixin would be mixed in as part of the object itself. So, perhaps interface delegates gives you slightly greater power than with a real mixin as you could reuse the surrogate mixin object. Then again, would you want to? I’ve not been able to think of a scenario where I would, but perhaps it could be useful.

I’d like to see interface delegates in C# at some point in the future (sooner rather than later). In fact, I’d like to see proper mixin functionality, but I recon that will require changes to the CLR to support multiple inheritance. In the meantime, I think I’ll have to write some sort of snippet in C# to quickly generate the code that Oxygene gives me in one line. Either that or start writing in Oxygene… Now, there’s a thought!

Crazy Extension Methods Redux (with Oxygene)

Back in April I blogged about a crazy thing you can do with extension methods in C#3.0. At the time I was adamant that it was a bad idea. I still think it is a bad idea, however, my thoughts have evolved a little since then and I have, possibly a solution to my hesitance to use said crazy feature.

So, if you can’t be bothered to click the link, here is a quick recap. You can create an extension method and call it on a null reference and it will NOT throw a NullReferenceException like a real method call would. At the time I was saying it was not best practice because it breaks the semantics of the dot operator which is used for member access.

Last night, I attended an excellent talk by Barry Carr on Oxygene, an Object Pascal based language that targets the .NET Framework. Oxygene has a very interesting feature, it has a special operator for dealing with calls on a reference that might be null. If that language can do it, what’s so wrong with the functionality that Extension methods potentially give? Semantics. Notice that I said that Oxygene has “a special operator”. It doesn’t use the dot operator. The dot operator still breaks if the reference is null. It has a colon operator. In this case if the reference is null (or nil as it is called in Oxygene) then the call to the method doesn’t happen. No exception is thrown.

For example. Here is the code with the regular dot operator:

class method ConsoleApp.Main;
var
  myString: String := nil;
begin
  Console.WriteLine('The string length is {0}', myString.Length);
  Console.ReadLine();
end;

And the result is that the NullReferenceException is thrown:

NullReferenceException

Here is the code with the colon operator:

class method ConsoleApp.Main;
var
  myString: String := nil;
begin
  Console.WriteLine('The string length is {0}', myString:Length);
  Console.ReadLine();
end;

And the result is that the program works, it just didn’t call the property Length as there was nothing to call it on:

Result

At this point I really would like to show you what this looks like in Reflector to show you what is going on under the hood, however, I get a message that says “This item is obfuscated and can not be translated” and the code afterwards isn’t quite right. However, the crux of it is like this in C#:

int? length;

if (myString != null)

length = myString.Length;

Console.WriteLine(“The string length is {0}”, length);

Now, back to these extension methods. After seeing this I was thinking that perhaps my total unacceptablity of allowing a null reference to be used with an extension method was perhaps incorrect. In a normal situation with an accidental null reference exception being used the NullReferenceException wouldn’t be thrown at the point of the method call (after all, the null reference is actually being passed in as the first parameter in an extension method), but somewhere in the method itself. Normal good practice would place a guard block at the start of the method so that it would be caught immediately.

However, what if you wanted to create similar functionality to the colon operator in Oxygene and have it ignore the null reference and do nothing? Well, my advice would be to create a naming convention for your extension methods to show that null references will be ignored. That way you can get the functionality with a slight semantic fudge of the dot operator. Of course, you still have to do the work and set up guard blocks to handle the null situation yourself in the extension method.

Here’s an example:

class Program
{
    static void Main(string[] args)
    {
        string myString = null;
        Console.WriteLine("The string length is {0}", myString.NullableLength());
        Console.ReadLine();
    }
}

public static class MyExtensions
{
    public static int? NullableLength(this string target)
    {
        if (target == null)
            return null;
        return target.Length;
    }
}

Monitoring change in XML data (LINQ to XML series – Part 5)

This is the 5th part in a series on LINQ to XML. In this instalment we will look at monitoring changes in XML data in the XML classes added to .NET 3.5.

The XObject class (from which XElement and XAttribute, among others) contains two events that are of interest to anyone wanting to know about changes to the XML data: Changing and Changed

The Changing event is triggered prior to a change being applied to the XML data. The Changed event is triggered after the change has been applied.

An example of adding the event handler would be something like this:

XElement root = new XElement("root");
root.Changed += new EventHandler<XObjectChangeEventArgs>(root_Changed);

The above example will trigger for any change that happens in the node the event handler is applied to and any node downstream of it. As the example is applied to the root node this means the event will trigger for any change in the XML data.

The event handler is supplied an XObjectChangeEventArgs object which contains an ObjectChange property. This is an XObjectChange enum and it lets the code know what type of change happened.

The sender contains the actual object in the XML data that has changed.

Adding an element

Take the following example where an element is added to the XML data.

XElement child = new XElement("ChildElement", "Original Value");
root.Add(child);

In this case the ObjectChanged is Add and the sender is the XElement: <ChildElement>Original Value</ChildElement>

A similar scenario happens when adding an attribute. However, instead of the sender being an XElement it will be an XAttribute.

child.Add(new XAttribute("TheAttribute", "Some Value"));

Changing an element value

If the value of the element is changed (the bit that currently says “Original Value”) then we don’t get one event fired. We get two events fired. For example:

child.Value = "New Value";

The first event with ObjectChanged set to Remove and the sender set to “Orginal Value” (which is actually an XText object) and the second event with the ObjectChanged set to Add and the sender set to “New Value” (again, this is actually an XText object).

Changing an element name

If the name of the element is changed then the ObjectChanged property will be set to Name and the sender will be the XElement that has changed.

child.Name = "JustTheChild";

Changing an attribute name

Unlike changing an element value, when the value of an attribute changes the ObjectChanged property will be Value and the sender will be the XAttribute.

child.Attribute("TheAttribute").Value = "New Attribute Value";

Technorati Tags: ,,,

Tip of the Day #4 (Connection Strings in Config files)

From .NET 2.0 onwards a new and improved configuration management system has been put in place. You can now add a <connectionString> element to the config file and use it to place the connection strings to the database and then retrieve then in a consistent way in your application. It supports multiple connection strings too if you need to access multiple databases.

The config file looks like this:

<configuration>
...
   <connectionStrings>
    <add name="Default" connectionString="Server=(local);database=MyDatabase"/>
  </connectionStrings>
...
<configuration>

From the .NET application you can access the connection string like this:

connectionString =
    ConfigurationManager.ConnectionStrings["Default"].ConnectionString;

Just remember to add a reference to System.Configuration in your project and ensure that the code file is using the System.Configuration namespace as well.

Functional Programming in C#3.0

Oliver Sturm spoke to to Scottish Developers in Glasgow earlier this week to a packed room! His topic was Functional programming in C# 3.0.

The feedback was overwhelmingly positive and he received comments such as “Great code examples” and “very worthwhile”. So, if you missed last nights session, or you just want to review the code at a more leisurely pace then Oliver has them on his blog: http://www.sturmnet.org/blog/archives/2008/03/14/devweek-session-slides-and-samples-and-info/

Oliver is also talking to VBUG in Livingston next week on the topic of F#. For more information: http://www.vbug.co.uk/Events/July-2008/VBUG-SCOTLAND-F-with-Oliver-Sturm.aspx

Finally congratulations to everyone who won prizes last night from the T-shirts right up to the MSDN Premium Subscription.

Navigating XML (LINQ to XML series – part 4)

In my last few posts on LINQ to XML (part 1, part 2 and part 3) I’ve shown you a starter on navigating around XML data. In this post I’ll continue to show you how to navigate through XML data by showing you how to navigate around sibling elements.

First consider this code:

XElement root = new XElement("root",
    new XElement("FirstChild"),
    new XElement("SecondChild"),
    new XElement("ThirdChild"),
    new XElement("FouthChild"),
    new XElement("FifthChild"));

Which produces the following XML structure:

<root>

<FirstChild />

<SecondChild />

<ThirdChild />

<FouthChild />

<FifthChild />

</root>

We can access the ThirdChild with this code:

XElement child = root.Element("ThirdChild");

From that point, we can also get access to its siblings.

To access the siblings that occur before the element we have a reference to then we can use ElementsBeforeSelf. As with Elements this returns an IEnumerable<XElement> object which allows us to iterate over the result, like this:

IEnumerable<XElement> elements = child.ElementsBeforeSelf();

foreach (XElement element in elements)
    Console.WriteLine(element);

The result is:

<FirstChild />

<SecondChild />

Conversely, we can get the siblings that come after the element we have a reference to with ElementsAfterSelf. Like this:

IEnumerable<XElement> elements = child.ElementsAfterSelf();

The result in this case will be:

<FouthChild />

<FifthChild />

Technorati Tags: ,,,

Navigating XML (LINQ to XML series – Part 3)

In my last two posts (part 1 and part 2) I’ve been introducing you to the the new XML classes in .NET 3.5. In this post I’ll continue that and show you some of the ways to navigate through XML.

First of all, lets start with a simple hierarchy of XML elements:

XElement root = new XElement("FirstGeneration",
                    new XElement("SecondGeneration",
                        new XElement("ThirdGeneration",
                            new XElement("FourthGeneration"))));

Which looks like this when rendered as XML:

<FirstGeneration>

<SecondGeneration>

<ThirdGeneration>

<FourthGeneration />

</ThirdGeneration>

</SecondGeneration>

</FirstGeneration>

Also in the last post I used Element to get a specific element from the current element. For example:

XElement child = root.Element("SecondGeneration");

Elements

If root (or FirstGeneration) only had one child element called “SecondGeneration” then everything is fine, you get what you asked for. However, if it contains multiple children all called “SecondGeneration” then you will only get the first element called “SecondGeneration”.

For example, if you add the following to the code above:

root.Add(new XElement("SecondGeneration","2"));
root.Add(new XElement("SecondGeneration","3"));

You will get a piece of XML that looks like this:

<FirstGeneration>

<SecondGeneration>

<ThirdGeneration>

<FourthGeneration />

</ThirdGeneration>

</SecondGeneration>

<SecondGeneration>2</SecondGeneration>

<SecondGeneration>3</SecondGeneration>

</FirstGeneration>

If you want to get all those additional children called “SecondGeneration” you will need to use the Elements (note the plural) method. For example:

IEnumerable<XElement> children = root.Elements("SecondGeneration");

You’ll also note that we don’t get a collection returned but an enumerable. This give us the opportunity to exploit many of the new extension methods. But I’ll leave them for another post. For the moment, we just need to know that it make it easy for us to enumerate over the data using a foreach loop. For example:

foreach (XElement child in children)
{
    Console.WriteLine(child);
    Console.WriteLine(new string('-', 50));
}

This will write out:

<SecondGeneration>

<ThirdGeneration>

<FourthGeneration />

</ThirdGeneration>

</SecondGeneration>

————————————————–

<SecondGeneration>2</SecondGeneration>

————————————————–

<SecondGeneration>3</SecondGeneration>

————————————————–

Parent

Using the same root object as above, we can see how to navigate back up the XML tree using Parent.

XElement grandchild = root.Element("SecondGeneration").Element("ThirdGeneration");
Console.WriteLine(grandchild.Parent);

The result of the code will be that the SecondGeneration element is printed.

 

Technorati Tags: ,,,

Crazy Extension Method

Here is an example of a crazy extension method that alters the semantics of method calling.

First the extension method:

public static class MyExtensions
{
    public static bool IsNullOrEmpty(this string target)
    {
        return string.IsNullOrEmpty(target);
    }
}

Instead of calling the static method IsNullOrEmpty() on string, we are turning it around to allow it to be called on a string type like an instance method. However, as you can probably tell, it may be called when the reference to the string is null. Normally this would result in an exception to say that you are attempting to call a method on a null value. However, this is an extension method and it actually works with nulls! This is probably not the best idea in the world, to be diplomatic about it.

Here is some calling code:

string a = null;
Console.WriteLine(a.IsNullOrEmpty());

Normally, an exception will be thrown if IsNullOrEmpty() is a real method. However, it isn’t in this case and the application happily writes “True” to the console.

 

Fizz-Buzz in LINQ

This just occurred to me. It is somewhat pointless, but I thought it was interesting:

static void Main(string[] args)
{
    var result = from say in Enumerable.Range(1, 100)
                 select (say % 15 == 0) ? "BuzzFizz" :
                    (say % 5 == 0) ? "Buzz" :
                        (say % 3 == 0) ? "Fizz" : say.ToString();
    foreach (string say in result)
        Console.WriteLine(say);
}
Technorati Tags: ,,