How can I be a zero-bug programmer?

It is a short article again, but I was surfing on the internet and I found a perl. See this link. Actually, it is an old joke, but I’m in good mood and I find it pretty funny, so I copy that into this article.

Joe asks: “How can I be a zero-bug programmer and know what every character of my code will cause and affect?”
The answer: Don’t code at all.

Sometimes I think the same, there are no silver bullets and we aren’t bulletproof. However, sometimes I believe the myth of the super programmer (aka real programmer) and I believe that everybody can develop a very particular set of skills when he takes enough time and effort.

Posted in Stuffs & Links | Tagged , , ,

Macro, with or without you (C++)

Macros are the bluntest instrument of C and C++’s abstraction
facilities, ravenous wolves in functions’ clothing, hard to tame,
marching to their own beat all over your scopes. Avoid them.

C++ Coding Standards: 101 Rules, Guidelines, and Best Practices
by Herb Sutter; Andrei Alexandrescu

Writing programs is not always easy, but in the most of cases, it is a lot of fun. (Note: reading other programmers’ code and talking about programming are the same, if you are open minded enough. When you are not alone and you are working with other guys, you face that neither you nor the world is perfect, but when you can live with that, it isn’t a problem.) But sometimes the fun is a little too much. You are fed up of feeling like your project never will be done or you are too week to fix the bugs before the deadline. If it happens to me, I just start to write interesting code and weird programs, because it helps me to remember why programming is so beautiful.

Function-like macros are not safe, function-like macros are ugly and function-like macros are dangerous, Herb Sutter and Andrei Alexandrescu are completely right. But function-like macros are interesting, because the macro substitution is completely different from the ordinary logic of programming. C++ is a sophisticated and complicated tool, if you want to use it, you need thinking in a sophisticated way. Macros are simple like hammers and when you want to solve complicated problems with macros, then you must be crafty, because you need to find a creative way to overcome the lack of the capabilities of the macros.

Okay, we need a creative task, we want to write macros. In these days, I’m working on small C++ project and I frequently use the singleton and the flyweight patterns. I must write the following code again and again:

class MyClass {
  static MyClass& instance() {
    static MyClass inst;
    return inst;

It is a bit boring to write something again and again. (Do you remember the DRY principle?) So, how can we avoid the repetition? When I read the the paragraph about the copy constructor in the Google C++ Style Guide, the macro DISALLOW_COPY_AND_ASSIGN impressed me, because it seems so elegant. Could we express the singleton pattern in the same way? Of course we can.

#define SINGLETON(NAM) static NAM& instance() {static NAM inst; return inst;}

class MyClass {

However, it isn’t very good, because MyClass contains a member function (instance), that isn’t listed in the source files. (In other words, it makes the code less understandable.) And it isn’t very good, because there is a much better (and more crafty) implementation, which uses inheritance and a template class, see here. (Frankly, I just love write such class headers like class MyClass : Singleton<MyClass>. It seems so expressive.) I place the much better solution here, because it is so beautiful. (Note, that singleton classes are always uncopiable, it is a trivial attribute of singleton classes.)

template <class Derived>
class Singleton : Uncopiable //see the 'Google C++ Style Guide'
   static Derived& getInstance()
     static Derived instance;
     return instance;
   Singleton() {}

class MyClass : public Singleton<MyClass>
   // original contents of TestClass

Compare the macro solution to the template solution. I think you feel, that the template solution is much better. Remember, inline template functions should be applied instead of function-like macros. (I think you know the famous min function, which can be implemented either via macros or via inline template function, the two different code will be compiled to the same binary executable file, but the template code is more safe and more maintainable.) This example suggests that we always can use templates instead of macros and they are not worse at all, and likely it is very close to the truth.

The flyweight pattern is more complicated than the singleton pattern. I tend to implement it in the following way. (Of course it need not to be said that I use a better hash function and collision checking, and I don’t use inline functions when it is meaningless.)

#ifndef MYCLASS_H
#define MYCLASS_H

#include <iostream>
#include <map>
#include <tr1/memory>

class MyClass {
  typedef std::map<int, std::tr1::shared_ptr<MyClass> > INSTANCEMAP;
  static INSTANCEMAP instances;

  static MyClass& instance(int a, int b, int c) {
    int key = instance_keyfunc(a, b, c);
    INSTANCEMAP::iterator it = instances.find(key);
    if (it != instances.end()) {
      return (*((*it).second));
    } else {
      instances[key] = std::tr1::shared_ptr<MyClass>(new MyClass(a, b, c));
      return *(instances[key]);

  static void listInstances() {
    //list instances
    std::cout << "List of instances: ";
    for (INSTANCEMAP::iterator mit = instances.begin();
         mit != instances.end();
      std::cout << (*mit).first << ";";
    std::cout << std::endl;

  void printABC() {
    std::cout << "{a = " << a << "; b = " << b << "; c = " << c << "}" << std::endl;

  MyClass(int a, int b, int c) :
    a(a), b(b), c(c) {}

  static int instance_keyfunc(int a, int b, int c) {
    return a * 10000 + b * 100 + c;

  int a;
  int b;
  int c;

MyClass::INSTANCEMAP MyClass::instances;


I started to simplify this code with macros, I wanted to write something like:

class MyClass {
  FLYWEIGHT(MyClass, int, a, int, b, int, c);

A such macro is possible, but it isn’t easy, it uses other macros or a chain of macros. And after the last example, the singleton template, I don’t feel like writing a macro because a template must be much more cool. The hardest part of the flyweight pattern is the handling of the constructor parameters of the derived class, the constructor of the Flyweight template class gets only a hash value, and it uses only the hash value to distinguish the instances.

template <class Derived>
class Flyweight
  static Derived& getInstanceByHash(int hashValue);
  Flyweight() {}

class MyClass : public FlyWeight<MyClass>
  static MyClass& getInstance(int a, int b, int c) {
    return getInstanceByHash(hash_function(a, b, c));
  static hash_function(int a, int b, int c);
  MyClass(int a, int b, int c) : a(a), b(b), c(c) {...}

Short and sweet, macros are not interesting, but they aren’t very useful. I think a C++ a real programmer doesn’t need to use macros and when he does it, he want to feel himself an oldscool C programmer. Likely templates are invented to make life more boring, but they are beautiful enough and that’s why we use them.

Posted in C++ | Tagged , , , ,

An annoying typo (ActionScript 3.0 )

In the last days I’ve worked on the project Traced, in other words, I’ve coded pretty much in ActionScript3.0. It wasn’t bad at all, except a typo. It was nothing more than a small and boring semicolon, what I forgot to insert, but it just made my day … miserable. (Sorry, I feel, that the sentence “it made my day miserable” isn’t perfect, but I’m just a Hungarian guy, I hope you understand me, gentle reader.) So, I’ve debugged the following small typo for hours without any results:

var myString: String =
    "It is the first row, " +
    "it is the second row and "
    "it is the third row and" +
    "it is the fourth row.";

I treated the error in a very wrong way, I started to struggle with the debugger and I started to modify the program randomly instead of thinking. (Adding random modifications to the program is some sort of trial-and-error method, but sometimes I like to think that it is similar to car diagnostic. If your car doesn’t work and you are curious what is wrong with your car, likely you dismantle your car. That’s exactly what I do with my wrong programs. In this case, I dismantled my AS3 files for hours.)

I tend to promote that ActionScript 3.0 is almost the same like Java. (For example,here is a random blog article about this issue: “I was therefore pleasantly surprised to find that ActionScript 3 is actually quite a powerful language, and was syntactically similar to Java in many ways“. And here is a detailed analysis, its conclusion: “I think you’ll find that what Adobe has done is taken some of the lessons learned from what is right and wrong about Java and incorporated them into their development of the ActionScript 3.0 language.“) The typo of this article cannot cause headache in a Java program, because in Java, every statement must be terminated by a semicolon. But in ActionScript 3.0, the syntax is a bit different, see this: “Alternatively, if you omit the semicolon character, the compiler will assume that each line of code represents a single statement. Because many programmers are accustomed to using the semicolon to denote the end of a statement, your code may be easier to read if you consistently use semicolons to terminate your statements.

I remember, that the syntax of the new operator in AS3 is a bit different too and the C++-like int(myVar) casting notation is prefered, so I can mention at least three difference between AS3 and Java. I’m sure there are more differences. If I have more time, I will write a longer article about the differences.

Posted in AS3 | Tagged , , , ,

The deadline is apporaching, project Traced (ActionScript 3.0)

I’m sure you don’t know, what Traced is at all, so I’m going to tell a bit about of it. It is the name of a new game we are currently working on. When I write ‘we’, I mean our four-person team, Kaylin, Ben, Julia and me. What kind of game is it? Here is a long quote from Kaylin Norman:

Traced is a hacking type game set in a cyber-punk world where player plays a Grey Hat hacker. SecuDrone Industries has been an established company for some time; putting security programs in every major business and home system. Recently though, there have been reports of computer viruses and power surges worldwide. Evidence points to SecuDrone Industries as the culprit. In a bout of vigilantism the player will be tasked with the choice to either Defend Secudrone Industries by eliminating the evidence, or by investigating them in order to uncover the truth. Visually, the game will look like a normal computer screen with a “special” program created by the player loaded into it that renders hacking easier. The graphics will be minimal, as most of the files and nodes will be represented as primitive shapes.

In other words, Traced is an old-fashioned cyberpunk game, it will be looking like an old MS-DOS game which imitates an old terminal (and keyboard) based operating system. (Do you remember these early green Hercules monochrome monitors? That’s why green is the main color of the game.) If you think “I’m sure this game won’t be the next Angry bird, it sounds too complex”, then you are right, but we don’t want to conquer the world, we just want to create a small and unique and interesting and quality flash game, and I hope there are a small group of hardcore gamers who will really like our game.


And why I write about our game in my professional blog? Because we have a deadline, Sunday the 21th of October. It is an important milestone, we plan to launch the first playable demo of Traced on that day. The demo will contain almost every in-game feature and the 90% of the necessary programming & scripting, the main difference between the demo and the whole game is that the demo contains only two playable leverls (the whole game will contain 30+ levels). After the demo, the game design and the programming and the tools will be almost done (except the bugs) and the next part comes after than, the writing of the missing texts, the design of the missing levels.

Maybe the demo will be one or two days late, but we will finish it soon or later, we are very close to finish it. I worked in the last 48 hours on Traced and I will work on it also in the next days. (Sad, but tomorrow I will have to travel a bit, so I’m off tomorow, after than I’ll continue the work.) I find the programming pretty intriguing, because I have to write pretty much working and bug-free code in very short time. So I don’t have enough time to write documentation or to draw UML class diagrams to design the structure of the program. Yes, it is some sort of agile development, and frankly, I really enjoy it. “I’m glad it has a name.

Imagine the following hypothetical situations. You are coding a windowing system with various components and different prefabricated windowses (these windowses are represented by OO classes). You just finish a complex window with a lots of built-in components and you suddenly mention that the next window that you have to create is very similar to the last window, there are only 5 or 6 minor differences. What do you do? If you have enough time, likely you design a decent base class to these windowses or you design the next window in the same way like the last window, step by step. (It is up to the current situation, both of them can be a good solution.) But if you don’t have time, you just add some extra attributes to the existing class in no time, and through these attributes and some constructor arguments, you can transform the existing window into the new window.

Is it a good practice? Not always. When it is a large project and you know that you will extend it in the future, then a such “quick and dirty” solution can cause very much inconveniences. But if it is a small in-game window and you will never change it, then likely the quick solution is the best soultion. Time is always money, if you don’t take care for design, you will have more time for implementation, testing and debugging. You have to take the alternatives into consideration, you have to make your own decision and that’s why the agile development is damn interesting.

Posted in AS3 | Tagged , , , ,

Learning the VI editor – First steps

I started to learn using the VI editor. The main reason, that I like to hack small programs on Linux. The GNU tools, gcc and g++ and automake are fascinating to me, OpenGL is always ready to show some graphics and you don’t need these big and fatty and boring IDEs like Eclipse and Visual Studio, all you need is a bare text editor and a linux shell. (And maybe some programmer’s fuel, Diet Coke in my case.)

I used gedit until now, it is simple enough but it isn’t very effective. (However, it provides at least syntax highlighting.) I read it on the internet somewhere, that vim provides some sort of auto completion and auto indenting, and that’s why I want to know more about it. I found a free book and I started to practice vim. I created a small tutorial to myself about basic things, here is it:

I remember I had a Unix course at the university and my teacher told: “VI is awful, the only one thing, that you should learn about VI, that how to close it, because it isn’t trivial at all and maybe somebody starts VI by accident“. I bet most people think the same. But it doesn’t stop my curiosity.

Posted in Linux | Tagged , , ,

Face it, Tiger

I promised that I wouldn’t write about personal things, but every rule has an exception. (Okay, this issue about rules and exceptions is not so trivial, please, examine the exception paradox if you are interested in.) Likely I’ll never forget this day, so I started looking for something that is similar to my emotions, like a picture or a song, something that represents my feelings. This is the best I’ve found so far:

I’m also quite amazed like Peter Parker, but in my case it isn’t because of a girl. I don’t make more comments to this picture. If you don’t know the Amazing Spider-Man #42 and the story behind the picture (shame on you!), I would recommend the following links: collection of face-it-tiger pictures and Mary Jane on Wikipedia.

Posted in Personal | Tagged

The XOR swap (Programming hacks)

Okay, it is a well-known (and not a very useful) trick, but I must write about it because I’ve never heard about before, and it seems like some kind of magic. Each programmer knows that if he want to swap two variables then he needs to use a third, temporary variable (or temp variable), which stores the value of the first variable while you copy the content of the second variable into the first variable. It is the general case, it works for strings, objects, it works for anything:

void swap(Something& a, Something& b) {
  Something temp;
  temp = a;
  a = b;
  b = temp;

I remember I was thirteen when I read first time about this technique. I found it in an old Hungarian Commodore64 programming book and this book had a chapter about sorting algorithms like selection sort, insertion sort, bubble sort and quicksort. (The details about the famous radix sort in linear time wasn’t written, just a short reference to that.) Examine the picture below!

Figure 1: The good old swap algorithm from a Hungarian book, highlighted in green. (Hartányi-Lengyel-Obádovics-Reményi: Számítástechnika C64, 1989)

It was pretty interesting. Later, I learnt that swap is a cool technique when you want to develop exception-safe C++ applications (see copy-and-swap), so swap and me became the best friends. And up until yesterday, I’ve thought it is a such easy story. Yesterday I’ve been looking for job interview questions, and I’ve founded something very interesting.

Write a C program to swap two variables without using a temporary variable.

I never thought that swap is possible without a temp variable. It is the so-called xor swap algorithm, it has also a page on the Wikipedia. Strange, but this method isn’t based on xor or addition-subtraction, it is based on group theory. Let S be a set of elements, let f(s,t) be a function and let s,t be elements of S. Suppose (S, f) is an abelian group and g is the inverse function of f in this group. The key idea, that g(f(s,t),t) = s and g(f(s,t),s) = t are always true. (These equations are simple, the definition of the inverse function and the commuativity were used. g(f(s,t), s) = t true iff the group is commutative, examine the equations g(f(s,t),s)=g(f(t,s),s) and f(s,t)=f(t,s)!) In other words, we can combine the values of s and t with the function f and we can extract the s from the combined value with g and t. Here is the pseudocode:

void swap(Something& s, Something& t) {
  t = f(s,t); //combined value
  s = g(t,s); //combined value unlocked with s, the result is t
  t = g(t,s); //combined value unlocked with t, the result is s

It seems cool, doesn’t? (Z,+) and (Z, xor) are abelian groups (Z is the set of integers), in the xor case, f = g = xor, which makes the xor swap more attractive. (Z, and) is not an abelian group, because N and 0 is always 0. There are only two binary connectives that are appropriate to construct a tricky swap functions, the xor and the logical biconditional (== NXOR).

(Okay, there is a small cheat in the last paragraph. Instead of Z we must use a cyclic set, because a 64 bit integer variable cannot store any possible integer values …)

Posted in Hacks | Tagged , , ,