sobota, 14 września 2013

Wrocław C++ Users group - presentation on C++03 idioms

It turned out that I'll be presenting idioms in C++03 this thursday (17.10.2013). Feel free to come.
You can find details here.

See you!

poniedziałek, 2 września 2013

Article in Polish developer journal "Programista"

I'm glad to announce that my article "Tricks and idioms in C++" ("Sztuczki i idiomy w C++") was published in polish developer journal, "Programista".
The journal is available in paper and e-paper forms. Click here for an description.

cover page

wtorek, 14 maja 2013

Surprising "dark corner" in C++

UPDATE 21.07.2013: Surprising dark corner turned on to be a compiler bug. Anyway, I think it is worth to know how name lookup works in detail.

Today was supposed to be a normal developer day. We have found something extremely surprising regarding C++, though. At least for us. Maybe someone will eventually provide reliable explanation on SO as my Google-fu (actually, more duckduckgo-fu recently :-) ) seems to have worsened.

This is a MWE of what I'm talking about:
 1 template <typename T> class Widget { };
 2 
 3 class Base
 4 {
 5 public:
 6     virtual void handle(Widget<float> widget) { }
 7     virtual void handle(Widget<int> widget) { }
 8 };
 9 
10 class Derived : public Base
11 {
12 public:
13     virtual void handle(Widget<int> widget) { }
14 };
15 
16 int main(int, char **)
17 {
18     Derived * derived = new Derived();
19     derived->handle(Widget<float>());
20     delete derived;
21 }
The code is not complicated. It is even not complex. We have some empty Widgettemplate class that is used as an argument. Below two classes are defined - Base andDerived. All methods in base class are virtual. Derived class does not provide implementation for a method that accepts Widget<float> as an argument. In main function we simply try to invoke this method.

We expect that Base::handle(Widget<float> const& widget) is going to be called. However before we run this simple program, we got compilation error.
$ clang++ polym.cpp
polym.cpp:20:21: error: no viable conversion from 'Widget<float>' to 'Widget<int>'
    derived->handle(Widget<float>());
                    ^~~~~~~~~~~~~~~
polym.cpp:1:29: note: candidate constructor (the implicit copy constructor)
                      not viable: no known conversion from 'Widget<float>' to
      'const Widget<int> &' for 1st argument;
template  class Widget { };
                            ^
polym.cpp:13:37: note: passing argument to parameter 'widget' here
    virtual void handle(Widget<int> widget) { }
                                    ^
1 error generated.
Wait, what has just happened? Did compiler just tried to perform implicit conversion fromWidget<float> to Widget<int>? Why? I'm afraid I can't give you precise answer. This was tested on gcc-4.7.2 and clang-3.0.

I suspect that compiler finds other methods with similar signatures and tries to match template parameter. Other lookup branches are dropped, so signature is not found in base class too. After it turns out that there is no exact match, implicit conversions are employed. Another option is that in such situations methods are shadowed, but that would be against polymorphism. Those are only my suspictions, do you have other ideas?

The question is open. So far I'm aware of two solutions.
16 int main(int, char **)
17 {
18     Derived * derived = new Derived();
19     dynamic_cast<Base*>(derived)->handle(Widget<float>());
20     delete derived;
21 }
10 class Derived : public Base
11 {
12 public:
13     virtual void handle(Widget<int> widget) { }
14     using Base::handle;
15 };
The first solution is rather straightforward. The other one is pretty curious, though.

czwartek, 7 marca 2013

Lectures at Wrocław University of Technology and University of Wrocław

Next week I'm going to conduct two lectures about C++ "Templates, STL, and Boost". Don't hesitate to come if you hang around.

First lecture
Place: University of Wrocław
Date: 25.03.2013

Second lecture
Place: Wrocław University of Technology
Date: 27.03.2013

wtorek, 9 października 2012

Handler mechanisms: design patterns

What really is a handler? What is main handling mechanism? These two questions appear on my mind when I start writing this post. Let me explain meaning of these words before I start, so no misunderstanding can actually happen. A handler is a procedure (stored as a function, method, or functor) that perform individual task according to given parameters. Usually there are a lot of handlers that accept same set of arguments and one main handling mechanism that decides which handler should handle particular "request". Main handling mechanism is simply a procedure that stores references to all registered handlers and executes respective one on demand. Handling mechanism should hide all unnecessary details from the end-user as he does not care how things are really handled. In this post I'll try to depict designs that can be used in order to implement such a "design pattern".

We start with C. The first thing that comes into mind is switch-case expression. Let's see how actually code looks like by defining three different handler functions and one controller.
int handlerA(int param) { return param + 1; }
int handlerB(int param) { return param + 2; }
int handlerC(int param) { return param + 3; }

int handle(int code, int param)
{
    switch(code)
    {
        case 0: return handlerA(param);
        case 1: return handlerB(param);
        case 2: return handlerC(param);
        default: assert(!"No handler registered for provided code");
    }
}
Nothing really interesting happens here. When new handlers are needed, the switch statement must also be modified. On the other hand invocation time when running program is really minimal (everything is computed at compilation-time). This approach may be good for small projects that have small amount of handlers.

Moving forward we can discover another approach - array of function pointers.
int handle(int code, int param)
{
    static int (*handlers[])(int) = { handlerA, handlerB, handlerC };
    static const int numHandlers = sizeof(handlers) / sizeof(handlers[0]);
    assert(code > 0 && code < numHandlers && "No handler registered for provided code");
    return handlers[code](param);
}
In terms of performance there is no meaningful difference between these two approaches. What we gain is less characters typed on the keyboard and more concise (in my opinion) design. Note that we have to add strict bound checking to avoid SIGSEGVs or other sort of problems.

We can easily redesign function array approach to use methods. The code would be pretty similar, so I won't write it down here. However, to improve our design we can use boost library as shown below.
class Handlers
{
public:
    int HandlerA(int param) { return param + 1; }
    int HandlerB(int param) { return param + 2; }
    int HandlerC(int param) { return param + 3; }
};

int main(int ac, char ** av)
{
    Handlers handlers;
    std::vector<function<int(int)> > fs;
    fs.push_back(bind(&Handlers::HandlerA, ref(handlers), _1));
    fs.push_back(bind(&Handlers::HandlerB, ref(handlers), _1));
    fs.push_back(bind(&Handlers::HandlerC, ref(handlers), _1));
    ...
}
For small project this approach could be inefficient: implementation requires additional dependencies. In bigger projects that already use boost libraries (what is common), this is not a big deal.

boost::bind documentation says that not using boost::ref results in pass-by-value behavior. I tried that and noticed that single bind produces eight calls to copy constructor! Maybe my opinion could be considered as premature optimization, but I advise to use boost::ref anyway.

In all previous approaches there were no possibility to add handlers at run-time. Eventually we got to this place. On the other hand, performance is decreased a little bit.

Okay, I have just mentioned that new handlers can be "registered" in run-time. However it's hard (at least for me) to imagine in what kind of situation this could be helpful. Maybe you do have any ideas? In the meantime let's concentrate on more practical approaches.

Imagine set of of handlers that register themselves automatically within the main handling class. Adding new handler doesn't require any changes in main handling mechanism. Moreover, there is no central point, where all handlers are defined, so we achieve "distributed" system. Usually when we solve this kind of problems we end up with something similar to code showed below.
class IHandler
{
public:
    virtual void Handle(void * data) = 0;
};

class HandlerA : public IHandler
{
public:
    virtual void Handle(void * data)
    {
        // Handle data here...
    }
};

class MainHandler
{
public:
    void Handle(int code, void * data)
    {
        _handlers[code]->Handle(data);
    }

    void RegisterHandler(int code, IHandler * handler)
    {
        _handlers.insert(make_pair<int, IHandler *>(code, handler));
    }

private:
    map<int, IHandler *> _handlers;
};
This approach forces developer to add somewhere a code that will register his class to the central point. How it can be done differently? Take a look at following snippet.
class IHandler
{
public:
    virtual void Handle(void * data) = 0;
};

class MainHandler
{
public:
    static void Handle(int code, void * data)
    {
        _handlers[code]->Handle(data);
    }

    static void RegisterHandler(int code, IHandler * handler)
    {
        _handlers.insert(make_pair<int, IHandler *>(code, handler));
    }

private:
    static map<int, IHandler *> _handlers;
};
map<int, IHandler *> MainHandler::_handlers;

template <typename T>
class AutoRegister
{
public:
    AutoRegister()
    {
        MainHandler::RegisterHandler(T::HANDLED_CODE, new T());
    }
    void fun() const { return; }
    ~AutoRegister()
    {
        // OPT: Unregister here...
    }
};

class HandlerA : public IHandler
{
public:
    virtual void Handle(void * data)
    {
        // Handle data here...
    }

    static int HANDLED_CODE;

private:
    static AutoRegister<HandlerA> _autoRegisterer;
};
int HandlerA::HANDLED_CODE = 1;
AutoRegister<HandlerA> HandlerA::_autoRegisterer;

// Example usage:
int main(int ac, char ** av)
{
    MainHandler::Handle(1, NULL);
}
As you can see there is no registration code inside a class that is a handler. Instead, we have to put two additional fields into the class that will automatically register a class in which they are defined to the central handling mechanism. In other words registration code may be unified and developer can just add few lines in order to define new handler. We can even employ CRTP pattern here, so defining new handler is as simple as just deriving from other type, but I'd prefer to stop things before they become uncontrollable. We must keep in mind that static initialization as shown above has its own problems. Arseny Kapoulkine has written a great post about dangers that come with this approach -"Death by static initialization" and I advise to read this post before implementing anything.

There are variety of design patterns related to handling mechanisms. Choosing right one strongly depends on multiple conditions. Switch and array based solutions have that advantage that they are thread-safe and relatively fast. When handlers are supposed to be added in run-time we can pick up some OO-based solution with e.g. vector. For convenience some auto-registering functionality may be used, but used with extremely care.

At the end of this post I'd like to compare C++ solutions with one python implementation - just to see dynamically-typed language in action. Take a look at following three code snippets: handler interface, example handler, and main handling mechanism respectively.
class BaseHandler(object):
    __metaclass__ = abc.ABCMeta

    @abc.abstractmethod
    def Handle(self, data): pass

    @abc.abstractproperty
    def code(self): pass
class ConcreteHandler(BaseHandler):
    code = 1
    def Handle(self, data):
        pass # Handle here...
class MainHandler(object):
    def __init__(self):
        self.__handlers = dict([
            (x[1].code, x[1]())
            for x in inspect.getmembers(sys.modules[__name__])
            if (issubclass(x[1], BaseHandler) and x[1] != BaseHandler)
        ])

    def Handle(self, code, data):
        try:
            return self.__handlers[code].Handle(data)
        except KeyError:
            raise RuntimeError('No handler registered for code ' + str(code))
That magic is, however, natual consequence of dynamically-typed language such as python which provides, in my opinion, great balance of power and readiness :-).

Natural continuation of this post should be review of possibilities in C++11. Do you have any remarks in this area? I'm curious how much it can help in such areas. Maybe it can't improve design very much, but I wouldn't be surprised in case of some killer C++11 feature, though. Share your ideas in comments!

środa, 26 września 2012

A perfect continuous integration system

One of the fundamental concept of agile software development is Continuous Integration (CI). You can read more about it here, for instance. In this post I'll try to define elementary things that in my humble opinion could build a ground for perfect continuous integration environment. Your comments on my concept will be also appreciated.

For this post I assume GNU environment, and statically-compiled languages like C++. However, such recipe can be easily rearranged to other compilers, languages, and environments.

1. CI server
First things go first. In order to facilitate the concept of CI we need some kind of automation software. Amount of this kind of software is fair big, so we can pick up one that fits our needs. The most popular is Jenkins (derivative from Hudson), as it is free and covers a lot of functionality. It is also easily extendable, thanks to over 400 plugins. From the other side, we have commercial applications, like for instance, Bamboo by Atlassian. I can't compare these two, but I assume that such a comparison would be similar to comparing MS Word with OpenOffice.org. For full list of well-known CI servers refer to this list.

2. Unit & Module tests
When we have our CI server running we are able to start defining jobs it will take car of. I do not mention basic "build" job, as it is obvious. Every knows that good code should be tested as much as possible. We can distinguish between standard Unit Tests (UT), that are likely to be written by developers and Module Tests (MT), that are preferably written by software testers. Personally I prefer to have one test runner to evaluate all UT and MT tests. This runner should output report in a form that is consumable by the CI server.

3. Lint for code and documentation
Before development on specific project is started, it is good idea to establish kind of coding convention and have a tool that will check whether software that is written follows rules specified in that document. This tool can be merged with standard lint tools like, for instance, this one, so hard-to-find errors are reported in the early stages of software development. Examples of such errors are: uninitialized variable, lack of assignment operator while copy constructor is defined, and so on.
We should also pick documentation system like, for example, doxygen and a tool that will check whether documentation is well written. People tends to ignore that, which is sad, because undocumented code is kind of useless for future maintainers and developers.

4. Coverage and profiling
When we have UT and MT integrated into our automation process, we likely are want to know how much code is really tested and what is overall performance of this code. For former case we have tools like gcov that will help us determine final test coverage in percents. For latter case there is available gprof, which output can be reorganized, so CI server can handle it. Example of such a tool is gprof2dot.py. This simply way we are able to see call graphs directly from our CI site and find out bottlenecks in the software we are developing.

5. Memory leaks hunter
Another thing that may be useful is tracing memory leaks (in case of languages that are statically compiled). We can use tool like valgrind to perform such operations. By using dedicated plugins for our CI server we are able to see overall trend of memory that was leaked in the software during run-time and figure out from where those leaks come from.

6. Cyclomatic complexity
Cyclomatic complexity helps us to determine how complex the software under production actually is. You can find more information about it here. I find this kind of tools very useful, therefore they are included in this list.

That's it! If you think that something crucial is missing here do not hesitate to write your opinions in comments!

poniedziałek, 3 września 2012

Moving to Nokia Siemens Networks

I decided to change company I work for few days ago. Today it's my first day I am working for Nokia Siemens Networks.

I would like to kindly thank to everyone who worked with me during last years. I consider Gigaset AG as a place of competeness and cooperation. I wish my new employeer could offer me at least similar possibilities I met at Gigaset AG.