# Tuesday, March 09, 2010
The iPhone is a fabulous device, few people will argue about that.

But...

When I started developing iPhone apps about a year ago, it felt... awkward. If you want to create an app for the iPhone, you have to use Objective C, which was invented sometime around 1934. I'm kidding of course: it was 1986, but that's a small detail.

Apart from the odd syntax (which is fine, other languages have odd syntax as well), I was amazed by the lack of basic language and framework features we take for granted these days.

To illustrate the contrast, I'll show a small function that strips the time portion of a date, written in Objective C:

+ (NSDate *) stripTime:(NSDate *) date {
NSCalendar *gregorian =
[[NSCalendar alloc]
initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *components =
[gregorian components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)
fromDate:date];

date = [gregorian dateFromComponents:components];

[gregorian release];

return date;
}

That seems a little verbose to me.

To put this in perspective, here's the C# code:

public DateTime StripTime(DateTime date)
{
return date.Date;
}

I guess I have been spoiled by C#. Can you imagine what it would be like to consume a SOAP webservice from Objective C? Well, check this out. (I have to admit: it received a 5-star rating, so I guess it was worth the 62 hours spent on it)

PS. I realize I suck at Objective C, and I'm sure a better Objective C developer can shave off a line or 2 of my code, but you get the picture...

Thank god a few geniuses over at Novell created MonoTouch...

kick it on DotNetKicks.com
Tuesday, March 09, 2010 10:53:03 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [7] -

# Friday, November 28, 2008

We all love unit tests (do we?). Yes we do (repeat 100 times). And we all love mocking for making life easier, but sometimes we just want to write some simple unit tests that don't require any mocking at all, because the code you are testing is easy to test without having to resort to all those mocking tricks

But what if you need to test code that relies on the date or some elapsed time? Let's say you wrote a simple caching class that automatically removes items from the cache when a certain amount of time has passed since the last access. It's tempting to slap some Thread.Sleep() calls in there to trigger expiration of cache items, but that will slow down your unit test, and most importantly, it's not accurate. What if you want to test some edge cases? Like, what happens when you access an item at the exact timeout period?

A few years ago I worked with a brilliant Java architect who simply said: "just mock the time!". What he meant was that I should create a fake DateTime class which behaves like the real DateTime class with one important difference: YOU control the time, not the system clock.

How is that done?

Simply create an interface with a single getter property of type DateTime:

public interface ITimeProvider 
{
   DateTime Now { get; }
}

Then you create 2 classes that implement this interface: one that returns the real time, and one that can be used to control a "fake" time:

public class RealTimeProvider : ITimeProvider
{
    public DateTime Now { get { return DateTime.Now; } }
}

public class MockTimeProvider : ITimeProvider
{
    private DateTime _time;

    public DateTime Now { get { return _time; } set { _time = value; } }
}

Of course the class(es) you want to test should be aware of this. For example, our cache class could look like this:

public class Cache
{
     private ITimeProvider _time = new RealTimeProvider();

     public ITimeProvider TimeProvider { get { return _time; } set { _time = value; } }

     // ... the rest of the class implementation
}

In our class implementation, all calls to DateTime.Now should be replaced by TimeProvider.Now.

And now the fun part, faking the time in our unit tests:

[Test]
public void TestCacheTimeout()
{
    ITimeProvider time = new MockTimeProvider();
    Cache cache = new Cache();

    cache.TimeProvider = time; // Tell our cache class to use our fake time

    cache.Add("A" , 1); // add an item to the cache

    Assert.IsTrue(cache.Contains("A")); // check if it's added

    time.Now += TimeSpan.FromHours(1); // let one hour go by...

    Assert.IsFalse(cache.Contains("A")); // check if it was automatically removed
}

That's pretty cool and simple, isn't it? Wouldn't it be nice if we could do the same in real life? ;-)

Next week I'll talk a little about unit testing multithreaded concurrency issues...

kick it on DotNetKicks.com
Friday, November 28, 2008 6:41:29 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] -
 |  |  | 
# 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] -
 |  | 
# 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] -
 |  | 
# Wednesday, August 22, 2007

This article may be extremely obvious to many people, but I am sure a lot of C# developers will be surprised by what will follow.

What's the difference between

MyType myObject1 = (MyType) anotherObject;

and:

MyType myObject2 = anotherObject as MyType;

Well, when "anotherObject" is assignable to MyType, both lines of code do the exact same thing, but when "anotherObject" is not of the correct type, the assignment to "myObject1" will throw an exception, but the second line of code will run fine and "myObject2" will be null.

Surprised? I was too, but it's in the C# specs.

FYI, the type cast is compiled to the "castclass" IL instruction, while the "as" version is compiled to the "isinst" instruction. Two different beasts

kick it on DotNetKicks.com
Wednesday, August 22, 2007 10:08:53 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [10] -
 |