# Tuesday, March 11, 2008

Like many tips & tricks concerning programming languages, what I will present here will be so utterly obvious to some C# developers, but could be an eye-opener to others.

How often do you write something like this?

        if (token == "A")
            tokenNumber = 1;
        else if (token == "B")
            tokenNumber = 4;
        else if (token == "C")
            tokenNumber = 5;
        else if (token == "X")
            tokenNumber = 10;
        else
            tokenNumber = 20;


How about writing it like this?

      tokenNumber = (token == "A") ? 1:
                    (token == "B") ? 4:
                    (token == "C") ? 5:
                    (token == "X") ? 10:
                                     20;


It's the same thing, but it looks cleaner, and the generated IL code is almost the same (it's even a bit shorter).

The reason this works is because the ternary operator (?:) is one of the few right-associative operators in C#. The other 2 are the assignment operator (=) and the lambda operator in C# 3.0 (=>)

kick it on DotNetKicks.com
Tuesday, March 11, 2008 2:33:05 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [24] -

# Friday, March 07, 2008

Every decent programming book tells you to write readable code. Few people do.

Code is read a lot more often than it is being written. Fact.

Programming style is all about personal taste. Agreed.

On the other hand, well... let's just take a very small piece of code from the BCL written by Microsoft:


    Type p = this;
    if (p == c) 
        return false; 
    while (p != null) {
        if (p == c) 
            return true;
        p = p.BaseType;
    }
    return false; 


Without changing any of the code (except spacing and indentation):


    Type p = this;
    
    if (p == c) 
        return false; 
    
    while (p != null) 
    {
        if (p == c) 
            return true;
        
        p = p.BaseType;
    }
    
    return false; 


I know the code is longer, and there are better examples to be found, but what makes code readable is being able to see the structure of the source code. This can be accomplished by using correct spacing, empty lines and correct placement of braces.

I especially want to stress the importance of using empty lines. Their primary purpose is to visually separate blocks of code. Note the example above. The original code has no empty lines whatsoever, which makes code very hard to read (even if you wrote the code yourself).

When should you use empty lines (IMHO) :

  • Before and after every control block ("if", "for", "while")
  • Before and after return statements
  • After blocks of variable declarations
  • After blocks of assignments
  • In between assignments if they "don't belong together"
  • (a curly brace counts as an empty line of course)

This is a small code fragment which illustrates some of these points:


    newSetMethod = typeBuilder.DefineMethod( /*ommitted*/ );

    ILGenerator ilGen = newSetMethod.GetILGenerator();

    ilGen.Emit(OpCodes.Ldarg_0);
    ilGen.Emit(OpCodes.Ldstr , baseProperty.Name);
    ilGen.Emit(OpCodes.Ldarg_1);

    if (baseProperty.PropertyType.IsValueType)
    {
        ilGen.Emit(OpCodes.Box,baseProperty.PropertyType);
    }

    ilGen.EmitCall(OpCodes.Call,setFieldMethod,null);

    ilGen.Emit(OpCodes.Ret);


Of course, there's more to readability than inserting empty lines, but it's a point which is often neglected. The most often heard excuse is that it makes code shorter. (sigh)

I don't want to start a religious war, just trying to express a (strong) opinion.

kick it on DotNetKicks.com
Friday, March 07, 2008 9:04:43 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [16] -
 |  | 

How many times have you written some timing code around a method call? If the answer is never, move on, skip this article...

For timing purposes, I always use a simple "TimeRunner" class that allows you to accurately measure the time it takes to execute a specific method. A kind of "poor man's profiler".

The usage is very simple:

public class Program
{
    public static void MySlowMethd()
    {
        for (int i=0;i<1000000;i++) {}
    }
    
    public static void Main()
    {
        TimeSpan ts = TimeRunner.Run(MySlowMethod); // Run once
        
        Console.WriteLine("Time per invocation: {0}", ts);
        
        ts = TimeRunner.Run(1000, MySlowMethod); // Run 1,000 times
        
        Console.WriteLine("Time per invocation: {0}", ts);
    }
}


That's it.

Here's the class:

public delegate void Action(); // leave this out if you're using C# 3.0

public class TimeRunner
{
    protected TimeRunner() {}

    public static TimeSpan Run(int repeatCount, Action f)
    {
        Stopwatch stopwatch = Stopwatch.StartNew();

        for (; repeatCount > 0; repeatCount--)
            f();

        stopwatch.Stop();

        return new TimeSpan(stopwatch.Elapsed.Ticks);
    }

    public static TimeSpan Run(Action action)
    {
        return Run(1,action);
    }

    public static TimeSpan Run<T>(Action<T> action, T data)
    {
        return Run(1, action, data);
    }

    public static TimeSpan Run<T>(int repeats, Action<T> action, T data)
    {
        return Run(repeats, delegate { action(data); });
    }
}
 
kick it on DotNetKicks.com
Friday, March 07, 2008 12:04:30 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [2] -

# Wednesday, March 05, 2008

Constructing related .NET objects (an "object graph") from XML files is a familiar challenge to most developers out there. Although it is not hard to write something like that: just read the tokens and fill the appropriate objects.

In most cases, the code produced is not very readable and hard to maintain, because the problem is usually implemented in a linear fashion with lots of loops and repeated (or similar) statements.

When faced with this problem, I usually use the "Factory Method" pattern to implement this. The idea is that every object class has its own FromXml() method which creates its own object according to the XML node passed in as a parameter.

For example, let's suppose we want to create a customer object from an XML segment where the customer name is a child element and the customer ID is an attirbute like:

<Customer id="CUST1"><Name>My Customer Name</Name></Customer>


The factory method would look like this (I'm using C# syntax for object construction):

public partial class Customer
    {
        public static Customer FromXml(XmlNode xmlNode)
        {
            Customer customer = new Customer {
                                        Id = xmlNode.Attributes["id"].Value,
                                        Name = xmlNode["Name"].InnerText,
                                        Orders = new List<Order>()
                                    };

            return customer;
        }
    }

 
Now suppose each customer has a number of orders, which are located under the <Orders/> child element. So we use the Order object's factory method to create the Order object from the XML child nodes:

public partial class Customer
    {
        public static Customer FromXml(XmlNode xmlNode)
        {
            Customer customer = new Customer {
                                        Id = xmlNode.Attributes["id"].Value,
                                        Name = xmlNode["Name"].InnerText,
                                        Orders = new List<Order>()
                                    };

            foreach (XmlNode xmlOrder in xmlNode.SelectNodes("Orders/Order"))
                customer.Orders.Add(Order.FromXml(xmlOrder, customer));

            return customer;
        }
    }
    


Got the picture? Now let's pull it all together, and parse the following XML file to our object graph containing "Customers", "Orders" and "OrderItems":

<?xml version="1.0"?>
<CustomerList>
<Customer id="CUST1">
  <Name>Mr X</Name>
  <Orders>
   <Order number="5001">
    <OrderItems>
     <OrderItem>
      <Description>Item 1</Description>
      <Price>45.00</Price>
     </OrderItem>
     <OrderItem>
      <Description>Item 2</Description>
      <Price>99.00</Price>
     </OrderItem>
    </OrderItems>
   </Order>
   <Order number="5002">
    <OrderItems>
     <OrderItem>
      <Description>Item 3</Description>
      <Price>120.00</Price>
     </OrderItem>
    </OrderItems>
   </Order>
  </Orders>
</Customer>
<Customer id="CUST2">
  <Name>John Doe</Name>
  <Orders>
   <Order number="5003">
    <OrderItems>
     <OrderItem>
      <Description>Item 4</Description>
      <Price>550.00</Price>
     </OrderItem>
     <OrderItem>
      <Description>Item 5</Description>
      <Price>41.50</Price>
     </OrderItem>
    </OrderItems>
   </Order>
  </Orders> </Customer> </CustomerList>


And the code:

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load("test.xml");

CustomerList customerList = CustomerList.FromXml(xmlDoc.DocumentElement);

public partial class CustomerList : List<Customer>
{
}

public partial class Customer 
{
    public string Id { get; private set; }
    public string Name { get; set; }
    public List<Order> Orders { get; private set; }
}

public partial class Order
{
    public int OrderNumber { get; private set; }
    public List<OrderItem> OrderItems { get; private set; }
    public Customer Customer { get; set; }
}

public partial class OrderItem
{
    public string Description { get; set; }
    public decimal Price { get; set; }
    public Order Order { get; set; }
}

public partial class CustomerList
{
    public static CustomerList FromXml(XmlNode xmlNode)
    {
        CustomerList list = new CustomerList();

        foreach (XmlNode xmlCustomer in xmlNode.SelectNodes("Customer"))
            list.Add(Customer.FromXml(xmlCustomer));

        return list;
    }
}

public partial class Customer
{
    public static Customer FromXml(XmlNode xmlNode)
    {
        Customer customer = new Customer {
                                    Id = xmlNode.Attributes["id"].Value,
                                    Name = xmlNode["Name"].InnerText,
                                    Orders = new List<Order>()
                                };

        foreach (XmlNode xmlOrder in xmlNode.SelectNodes("Orders/Order"))
            customer.Orders.Add(Order.FromXml(xmlOrder, customer));

        return customer;
    }
}

public partial class Order
{
    public static Order FromXml(XmlNode xmlNode, Customer customer)
    {
        Order order = new Order {
                            OrderNumber = Int32.Parse(xmlNode.Attributes["number"].Value),
                            Customer = customer,
                            OrderItems = new List<OrderItem>()
                        };

        foreach (XmlNode xmlItem in xmlNode.SelectNodes("OrderItems/OrderItem"))
            order.OrderItems.Add(OrderItem.FromXml(xmlItem, order));

        return order;
    }
}

public partial class OrderItem
{
    public static OrderItem FromXml(XmlNode xmlNode, Order order)
    {
        return new OrderItem {
                                 Description = xmlNode["Description"].InnerText,
                                 Price = Decimal.Parse(xmlNode["Price"].InnerText),
                                 Order = order
                             };
    }
}


The advantages of using this pattern are obvious:

  • Very readable (and maintainable) code
  • The implementation details on how to read a particular type of object are located in the class itself, making it very easy to make a small change (for example adding a new property to an object)
  • Easy to read recursive object graphs
  • Properties that should be read-only can be made read-only (no messing with "internal" properties)

Note that a similar pattern can be used for writing objects to an XML file. Just create a member method "ToXml()".

kick it on DotNetKicks.com
Wednesday, March 05, 2008 9:03:02 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [4] -
 |  | 
# Sunday, March 02, 2008

A little sooner than expected, I decided to publish the source code for LazyParser.NET on CodePlex.

LazyParser.NET is a lightweight C# expression parser that allows you to add late-bound expression parsing to your .NET applications. It will allow you to use (user supplied?) C# expressions to be used in a variety of situations:

  • Validation expressions
  • Blog engines
  • Content management systems
  • Calculators
  • ...

The following features are supported in this release:

  • Full C# 2.0 expression syntax (exceptions listed below)
    • All numeric and boolean operators
    • Method calls (isolated and member/static methods)
    • Constructor calls
    • typeof() expression
    • All literals (numeric, character, string), including character and string escaping
  • C# 2.0 compliant (operator precedence, implicit conversions, nullable type lifting, type promotion, etc...)
  • Late binding
  • Field access interceptors at runtime
  • Support for member fields, properties and methods
  • Support for static fields, properties and methods
  • Function injection using delegates

Not supported in this release:

  • Indexing operator ( "[]" )
  • Conditional operator ( a ? b : c)
  • Unary operators (except "!", which is supported)
  • "is" and "as" operators

An example of how you can use this library:

ParserContext context = new ParserContext();
 
context.Add("Math", new ClassName(typeof(Math)));
context.Add("SomeString", "Hi there!");
context.Add("SomeNumber", 20);
context.Add("fmt",  new StaticMethod(typeof(String), "Format"));
 
CSharpParser parser = new CSharpParser();
 
string stringValue = parser.Evaluate<string>("fmt(\"I said: {0}\", SomeString)", context);  
// returns "I said: Hi there!" int intValue = parser.Evaluate<int>("Math.Max(10, SomeNumber)" , context);
// returns 20 double doubleValue = parser.Evaluate<double>("SomeNumber * 2.0", context);
// returns 40.0

 

This is just the first pre-1.0 release of this library, so there may be some small problems. Any suggestions for improvement or bug reports are more than welcome. Please use the CodePlex discussion area and the issue tracker for this purpose

UPDATE: LazyParser.NET v0.9.1 has been published on CodePlex, with support for indexing operators.

kick it on DotNetKicks.com
Sunday, March 02, 2008 11:33:19 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [6] -