Michael J.A. Clark
Michael Clark is a professional software developer who creates high-quality products for startups in Cambridge, UK. Skills: C#, Java, PHP, XHTML, AS3, CSS, ML.

Sections

Contact details

Email
mjac@mjac.co.uk
Skype
mjacdotuk
Twitter
mjacuk

Articles tagged coding

Debugging legacy C++ in Visual Studio’s output window

Sometimes you are knees deep in legacy code and need to know what is going on. Sensibly you try to debug and step through. However, seconds later Visual Studio has started to crawl and it looks like you are stepping over at one line per minute.

At this point, consider logging to console instead of continuing to debug. In many cases this can be a vanilla printf but sometimes a printf is dropped by the application and nothing is logged.

In cases where printf produces nothing, you can use the Visual Studio debug output window to get some idea of the state of the system:

// sprintf into a character pointer (128 bytes on the heap) and output ASCII
char *str = new char[128];
sprintf(str, "%d %d\r\n", arrayIndex, arrayValue);
OutputDebugStringA(str);

Thanks for reading, please add your comments.

MVC routing on legacy ASP pages

When working on legacy ASP websites often you have to work with a directory full of .aspx files:

  1. about.aspx
  2. login.aspx
  3. logout.aspx
  4. shopping.aspx
  5. ...

With some architectures, the code behind calls into a front controller as follows:

Protected Overrides Sub OnLoad(ByVal eventArgs As System.EventArgs)
    MyBase.OnLoad(eventArgs)

    Dim frontController As New LegacyFrontController
    frontController.LoadPage("shopping.aspx")
End Sub

Thanks to MVC route controllers, we can refactor such websites and reduce the amount of .aspx files.

All we need to do is create a method to add the route from each page to a proxy page for the front controller. The key here is pass the page as a data token so that, when frontcontroller.aspx is executed, it knows about the specific page requested.

foreach (string page in pages)
{
    var dataTokenDictionary = new RouteValueDictionary
    {
        { "page", page }
    };

    routes.MapPageRoute("route_" + page, page + ".asp",
        "~/frontcontroller.aspx", false, null, null,
        dataTokenDictionary);
}

Then to hook this new proxy page into the front controller, you just have to append the .aspx file extension back to the data token.

Protected Overrides Sub OnLoad(ByVal eventArgs As System.EventArgs)
    MyBase.OnLoad(eventArgs)

    Dim frontController As New LegacyFrontController
    frontController.LoadPage(RouteData.DataTokens("page") + ".aspx")
End Sub

This technique is a good middleground along the road to refactoring the whole website to MVC Controllers. It provides a clean website directory and makes it easier to change the behaviour of the front controller across all pages.

Thanks for reading, please add your comments.

Single return versus multiple return

Imagine the maitre d' at a restaurant. When a diner enters the restaurant the maitre d' has to perform a number of checks to determine whether the diner is allowed a table. When we take this real world scenario and convert it into code, we end up writing a validation function.

If the rules are:

  • Check the diner is old enough
  • Check the booking exists
  • Check the booking has not expired
  • Check there is a table available

Then we can write the code as follows:

public bool ValidateDiner(Person person, DateTime dateNow)
{
    bool valid = false;

    if (person.Age >= _Restaurant.MinimumBookingAge)
    {
        Booking booking = GetBooking(person.Id);
        if (booking != null)
        {
            TimeSpan timeUntilBooking = (booking.Date - dateNow).Duration();
            if (!(timeUntilBooking.TotalMinutes < _Restaurant.MaximumWaitingMinutes))
            {
                if (_Restaurant.HasTableAvailable())
                {
                    valid = true;
                }
            }
        }
    }

    return valid;
}

This code uses the principle of returning once. Although some programmers are productive results adhering to this rule, I would rewrite this function to have multiple return statements, to fail early and fail fast.

Here is a rewritten validation method with multiple return statements:

public bool ValidateDiner_EarlyExit(Person person, DateTime dateNow)
{
    if (person.Age < _Restaurant.MinimumBookingAge)
    {
        return false;
    }

    Booking booking = _GetBooking(person.Id);
    if (booking == null)
    {
        return false;
    }

    TimeSpan timeUntilBooking = (booking.Date - dateNow).Duration();
    if (timeUntilBooking.TotalMinutes < _Restaurant.MaximumWaitingMinutes)
    {
        return false;
    }

    if (!_Restaurant.HasTableAvailable())
    {
        return false;
    }

    return true;
}

Code Complete provides the following guidance on return statements:

  • Minimise the number of returns in each routine
  • Use a return when it enhances readability

Returning early does enhance readability in this example. The aim of the method is to cause input to fail validation and validation failure is the common case.

Another structural possibility is to decouple the validator from the validation rules with this schema:

private readonly List<Func<Person, bool>> m_listValidationRules = new List<Func<Person, bool>>();

public void AddRules()
{
    m_listValidationRules.Add(person => person.Age >= _Restaurant.MinimumBookingAge);
    m_listValidationRules.Add(person => _GetBooking(person.Id) != null);
    m_listValidationRules.Add(person =>
    {
        Booking booking = _GetBooking(person.Id);
        if (booking == null)
        {
            return false;
        }

        TimeSpan timeUntilBooking = (booking.Date - DateTime.Now).Duration();
        return timeUntilBooking.TotalMinutes >= _Restaurant.MaximumWaitingMinutes;
    });
    m_listValidationRules.Add(person => _Restaurant.HasTableAvailable());
}

public bool ValidateDiner_RuleList(Person person, DateTime dateNow)
{
    return m_listValidationRules.TrueForAll(validate => validate(person));
}

This can be useful when the rules are optional and/or require additional resources that the validator should not know about.

Thanks for reading, please add your comments.

Feature picks from C# 6

These are my feature picks from the upcoming C# 6:

New nameof operator

The nameof operator provides the name of the target variable. We can use it to prevent debugging messages becoming inconsistent after refactoring variable names.

if (!_Validate(name)) {
    throw new ArgumentException(nameof name + " is not valid");
    // throws "name is not valid"
}

Primary constructors

Primary constructors allow us to initialise fields and properties without a constructor.

Instead of having to perform an assignment in the constructor like this:

public class Cache
{
    private int _capacity;

    public Cache(int capacity)
    {
        _capacity = capacity;
    }
}

We can now use the shorthand:

public class Cache(int capacity)
{
    private int _capacity = capacity;
}

If you want to perform logic in the constructor, then you can call this():

public class Cache(int capacity)
{
    private int _capacity = capacity;

    public Cache(int capacity) : this(capacity)
    {
        m_oInnerCache = StaticCache.getInstance();
    }
}

However, in most cases this is not recommended.

Auto-property initialisers

You can initialise properties inline, instead of having to use the constructor:

public class BoardGame
{ 
    public int TurnLimit { get; } = 10;
}

This reduces the need for a constructor, especially when coupled with primary constructors.

Declaration expressions

You can declare an out parameter in an expression so that it is scoped tighter.

if(decimal.TryParse(test, out var amount))
{
    return amount;
}

Amount is not accessible outside the scope of the if-statement.

Further reading

Scott Allen has longer descriptions of each feature on his blog Ode to Code.

Thanks for reading, please add your comments.

Immutable C# Structs

This is a basic immutable struct in C#.

public struct PuppyDogPair
{
    public PuppyDogPair(Guid puppyId, Guid dogId)
        : this()
    {
        Puppy = puppyId;
        Dog = dogId;
    }

    public Guid Puppy { get; private set; }
    public Guid Dog { get; private set; }
}

If your struct is not immutable, then you will have to pass it by reference if you want to mutate it inside helper methods.

private static void PerformAction(ref Config config)
{
    // do something with config
    config.usages++;
}

One great way of using immutable structs is to fill existing result rows with additional information. This code iterates over a result enumerable and keys into an existing dictionary to fill it with more information:

// Get data from database
foreach (var row in rowResults)
{
    var lookupPair = new PuppyDogPair(row.puppyId, row.dogId);

    gridRow = gridRowDictionary[lookupPair];
    gridRow.BirthDay = row.BirthDay
    // ... push more results into grid row from row
}

Thanks for reading, please add your comments.

More articles on the next page