Vlad's blog

In programming veritas

Archive for November 2011

DisposableAction

with one comment

While programming is quite common situation where some logic is implemented in three phases:

  1. Initialization
  2. Business logic
  3. Finalization

In C# is commonly used for this operator using, which gets a reference to the IDisposable interface in the beginning of the block and calls the Dispose() method at the end. The problem is that the IDisposable interface is implemented at the class level while the initialization-logic-finalization strategy usually refers to the methods of the class. Suppose that we implement a class HtmlReportBuilder, which generates a HTML report. Method Begin() starts the procedure of constructing the report, creates a buffer for HTML content, and adds the required html and body tags. Methods InsertRow(), InsertSummary() implement some business logic of building a report. Method of Finish() adds the closing html and body tags and finalizes report generation.

class HtmlReportBuilder
{
    private StringBuilder _html;

    public string Html { get { return _html.ToString(); } }

    public void Begin()
    {
        _html = new StringBuilder();

        _html.AppendLine("<html><body>");
    }

    public void Finish()
    {
        _html.AppendLine("</body></html>");
    }

    public void InsertRow() {}
    public void InsertSummary() {}
}

This class is used as follows.

var builder = new HtmlReportBuilder();
builder.Begin();
builder.InsertRow();
builder.InsertSummary();
builder.Finish();

In this implementation, the call Finish() is optional, that is not very convenient. I would like to Finish() is invoked implicitly. For this problem, there is a fairly simple and elegant solution – DisposableAction.

public class DisposableAction : IDisposable
{
    private readonly Action _action;

    public DisposableAction(Action action)
    {
        _action = action;
    }

    public void Dispose()
    {
        if (_action != null)
            _action();
    }
}

DisposableAction class implements the IDisposable.The constructor receives a delegate that is invoked in the method Dispose().This class is used as follows.

class HtmlReportBuilder
{
    private StringBuilder _html;

    public string Html { get { return _html.ToString(); } }
        
    public IDisposable Begin()
    {
        _html = new StringBuilder();

        _html.AppendLine("<html><body>");

        return new DisposableAction(() =>_html.AppendLine("</body></html>"));
    }
}

Method Begin() now returns a reference to IDisposable, which can be used in using.

var builder = new HtmlReportBuilder();
using(builder.Begin())
{
    builder.InsertRow();
    builder.InsertSummary()
}
Console.WriteLine(builder.Html);

When application leaves the using block, it will automatically be invoked delegate, which will add the finishing body tags, and html.

Written by vsukhachev

November 8, 2011 at 4:02 am

Posted in Development

Tagged with ,

Smart pointers in C++0x

leave a comment »

Probably, it is difficult to find a programmer for C++, who is never used smart pointers. Dozens of implementations appeared that differ in strategy of ownership, implicit conversion and multithreading support. Before the advent of C++0x standard library offered only std::auto_ptr, which is not suitable for many situations. Of course, you could use Boost or Loki but only in C++0x smart pointers officially included in the standard.
So, what is smart pointer? This is a class that mimics the semantics of a pointer with the implementation of the -> operator and the operator * and frees the programmer from the control of the resource to which it refers. As a rule, smart pointers are implemented as template classes, providing access to the methods of the object referenced by. But before we begin a detailed review of new opportunities for C++0x in terms of smart pointers make a small digression.

Copy and move semantics

The concept of copy and move semantics is closely related to the topic of smart pointers, and is itself a topic for separate discussion. Here we discuss the basic definitions. Based on its definition copy semantics implies calling the copy constructor or assignment operator. Consider the following example.

void swap(int& a, int& b)
{
    int tmp = a;
    a = b;
    b = tmp;
}

There are three copy operations in this example. This is acceptable for int, but let us assume that we have to swap two strings. Let’s say string class has member char* data that points to null delimited string and member size_t size which is a length of string. Below is the implementation that uses move semantics.

void swap(string& a, string& b)
{
    const char* p = a.data();
    size_t sz = a.size();
    a.data() = b.data();
    a.size = b.size();
    b.data = p;
    b.size = sz;
}

Notice we were able to avoid using of time consuming copy operations. It is recommended to implement publicly available swap method for you classes. It can dramatically improve the performance when you use STL containers.

class A
{
    public:
        void swap(A& rhs); 
};

Read the rest of this entry »

Written by vsukhachev

November 4, 2011 at 11:25 am

Posted in Development

Tagged with