Monday, November 28, 2011

Understanding C++ Traits

Suppose we have a function that does this
if class is foo, use a new implementation
else use an old implementation
There are many ways to achieve this. The naive way is as shown below.
if (instance.type() == "foo") {
    instance.new_impl();
} else {
    instance.old_impl();
}
Another way is to use a runtime polymorphism as shown below.
class foobar_base {
public:
    virtual ~foobar_base() {}
    virtual void impl() = 0;
}

class foo : public foobar_base {
public:
    virtual ~foo() {}
    void impl() { 
        cout << "New implementation" << endl;
    }
};

class bar : public foobar_base {
public:
    virtual ~bar() {}
    void impl() {
        cout << "Old implementation" << endl;
    }
}

void do_something(const foobar_base& fb) {
    fb.impl();
}
If we need to avoid any runtime type check and use a compile-time type check, we can achieve it by leveraging on the C++ templates and use C++ traits to store the type information as shown on the example below.
#include <iostream>
using namespace std;

template<typename T>
struct impl_traits {
    static const bool value = false;
};

template<typename T>
void do_something() {
    if (impl_traits<T>::value) {
        T::new_impl();
    } else {
        T::old_impl();
    }
};

class foo {
public:
    static void old_impl() {
        cout << "[foo] Old implementation" << endl;
    }

    static void new_impl() {
        cout << "[foo] New implementation" << endl;
    }
};

class bar {
public:
    static void old_impl() {
        cout << "[bar] Old implementation" << endl;
    }

    static void new_impl() {
        cout << "[bar] New implementation" << endl;
    }
};

template<>
struct impl_traits<foo> {
    static const bool value = true;
};


int main() {
    do_something<foo>();
    do_something<bar>();

    return 0;
}
The output is
[foo] New implementation
[bar] Old implementation

Thursday, November 17, 2011

Multithreading in wxPython

This innocent code below looks okay, but it has one major bug here. The bug can cause the application to crash. This is because we try to perform some GUI related stuff in another thread (MyThread). Many GUI toolkits are single-threaded. In other words, the main loop (the loop that starts the GUI application) should only be responsible for handling any GUI related stuff. Any other long running tasks can be done in another thread.
#!/usr/bin/env python

import wx, threading

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "MyApp")
        panel = wx.Panel(self)
        
        self.btn = wx.Button(panel, label="Click Me!")
        self.btn.Bind(wx.EVT_BUTTON, self._do_something)
        
    def _do_something(self, evt):
        MyThread(self).start()
        
class MyThread(threading.Thread):
    def __init__(self, frame):
        threading.Thread.__init__(self)
        self.frame = frame
        
    def run(self):
        wx.MessageDialog(self.frame, message="Test", caption="Test",
                         style=wx.ICON_ERROR | wx.CENTRE).ShowModal()
                             
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MyFrame()
    frame.Centre()
    frame.Show(True)
    app.MainLoop()
To fix this bug, wxPython provides some thread-safe methods, such as wx.CallAfter, wx.CallLater, and wx.PostEvent. A combination of Publisher/Subscribe and wx.CallAfter can eliminate the bug as shown below.
#!/usr/bin/env python

import wx, threading
from wx.lib.pubsub import Publisher

class MyFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, None, -1, "MyApp")
        panel = wx.Panel(self)
        
        self.btn = wx.Button(panel, label="Click Me!")
        self.btn.Bind(wx.EVT_BUTTON, self._do_something)
        
        Publisher().subscribe(self._update, "update")
        
    def _do_something(self, evt):
        MyThread().start()
    
    def _update(self, msg):
        # msg.data is the data that was sent in the CallAfter
        wx.MessageDialog(self, message=msg.data, caption="Test",
                         style=wx.ICON_ERROR | wx.CENTRE).ShowModal()
        
class MyThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        
    def run(self):
        msg = "Test Message"
        wx.CallAfter(Publisher().sendMessage, "update", msg)
                             
if __name__ == "__main__":
    app = wx.PySimpleApp()
    frame = MyFrame()
    frame.Centre()
    frame.Show(True)
    app.MainLoop()

Tuesday, November 1, 2011

How to Create a JAR with Dependencies in Gradle

Creating a single executable JAR/fat JAR can be pretty useful. We can do something like this.
java -jar foobar.jar
In Maven, we need to write a pretty verbose XML to do that as shown in my previous blog. In Gradle, this task can be easily achieved in just few lines as shown in the example below.
apply plugin: 'java'

sourceCompatibility = 1.6
targetCompatibility = 1.6

defaultTasks = ['clean', 'jar']

dependencies {
   compile 'org.slf4j:slf4j-api:1.6.2'
   compile 'ch.qos.logback:logback-core:0.9.30'
   compile 'ch.qos.logback:logback-classic:0.9.30'
   compile 'javax.servlet:servlet-api:2.5'
   compile 'org.eclipse.jetty.aggregate:jetty-all:7.5.4.v20111024' 
   
   testCompile 'junit:junit:4.+'
   testCompile 'org.mockito:mockito-core:1.8.5'
}

jar {
   from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
   manifest { attributes 'Main-Class': 'test.Main' }
}