Keeping it Small and Simple


So your OO-programming lover cheated on you..

Filed under: Computer Programming, Humor — Tags: , — Lorenzo E. Danielsson @ 00:58

You even caught him right in the act, you say? Well, you are simply wrong. Let me explain.

You met him recently, right? What I mean is, you didn’t start dating when you were kids or anything. See, you’re in trouble right there. From early teens he’s been fantasizing about women. It’s at that age that the very idea of a woman came up. And attached to that fantasy were a bunch of attributes that he imagined “woman” to have.

You probably have all those attributes, but you see, long before you met him he had built this fantasy and now you are just a physical manifestation of those fantasies. It’s called late binding.

Now, I don’t doubt that he feels that you fulfill the fantasies that he began having as a teenager. But so does this other woman. Since you are late-bound, he can replace you with any other instance of a woman, as long as that woman also fulfills exactly the same fantasies (the position you found them in indicates that this is, in fact, the case).

What you’ve got here is not infidelity, it’s polymorphism. Go over to the mirror, look at yourself and tell yourself, over and over again, “I am just an object”. Then get over it.

Note that the same still applies if you are a man and the OO programmer is a woman. It also applies for same-sex couples. This is OO. It applies everywhere.


A study of programmers’ political preferences

Filed under: Computer Programming, Humor, Politics — Tags: , , — Lorenzo E. Danielsson @ 03:16

Since this year is an election year, and people are collecting all sorts of statistics on all kinds of groups, including but not limited to women, black people, latinos, journalists and dog owners. I thought I’d help out by presenting the political demographics (don’t have a clue about what that means, but it sounds impressive so I’ll use it) of computer programmers.

If you represent a major news broadcaster and would like to offer me a job as a political commentator after reading this, just send me a mail. You don’t need to tell me which station you represent, I can see that from you email address. All I need is how much you are offering, and the name of the person who’ll sit beside me. Actually, forget the last bit, I’m not interested, just send me her age. That’s it. One mail, two numbers: salary, age. Got it? Good.

The next paragraph is intentionally left blank. It is supposed to contain the standard mumbo-jumbo about the margin of error or whatever they call it, but to tell you the truth, I had a bad Tequila-induced hang-over during statistics class, so I’m leaving this as an exercise for the reader.

[ This paragraph intentionally left blank ]

C Programmers

The C stands for conservative. Grand ‘Ole Party, all the way.

Java Programmers

These are the neo-cons, in the truest sense of the word. They used to be liberal but now feel comfortable rubbing shoulders with C programmers. They haven’t noticed that C programmers despise them.

Perl programmers

Life-style anarchists. Legalize it, whatever it may be.

Python programmers

Important update
A person with connections to the python community has come out to correct us on this issue. Python programmers are actually communists, not fascists. The person who gave me this information is none other than the great, great, great, great, great, great, great grand-son of Brian. We Hail you, O Brian.

(Fascists). Communists. They want everything to be uniform. Indentation, coding style. Ideally everybody should use the same variable names. By the time Python 3000 comes out, Python programmers will be required wear the official Python uniform. There is a PEP about the official Python hairstyle, which will apply to both male and female programmers.

At Python rallies one can hear the battle-cry: “Exterminate Ruby!”. These cries are usually led my the fiercest and most notorious of the Python gangs, the infamous “Knights who say Ni”.

Ruby programmers

Naive liberals. This is the young crowd who think they’ve got it all worked out. They haven’t, but don’t tell them that. They’ll overwhelm you with arguments that could only make sense to a really young mind.

Historically, Ruby has its political roots in the life-style anarchism of Perl. Though there are a few Rubyists who still openly admit that “anarchism is cool”, most modern Ruby programmers pretend it’s all a historical lie. In fact, a large number of Ruby programmers are secretly conservatives. They are tomorrow’s Java programmers. They feel that they are being kicked upon and can’t wait until it’s their turn to do the kicking.

It has been found that a significant number of Ruby programmers of the Rails type are fairly paranoid, to say the least. They have conspiracy theories coming out of their as.. er, back sides. They favor Ron Paul.

PHP programmers

After many years of code abuse, most PHP programmers have been declared unfit to vote.

Haskell programmers

Haskell programmers have evolved beyond politics a long time ago. As a matter of fact, anybody who has truly mastered Haskell has achieved Buddhahood. Obviously one can not expect them to engage in worldly matters.

Ocaml programmers

Ocaml programmers are attracted to bureaucracy, and are ready to support any party that will ensure that life becomes as complicated as possible for citizens. Since Soviet-style communism is the best example of an overly complex society, this political philosophy has captured many Ocaml programmers.

Scala programmers

They are too young to vote, which is a good thing, because they are very young and very confused.

LISP programmers

LISP programmers statistically do not exist.

Scheme programmers

Will not vote, but they are developing a prototype of a politician that will be better than any other politician. He’ll do his basic arithmetic backwards, but somehow he will still be superior.

Mono/.Net programmers

The only thing I was able to learn about this crowd is that they are so accustomed to constant change that they cannot imagine supporting the same candidate, or even the same party, for two consecutive elections.

Final note: I tried to interview a few Pascal programmers, but they were all too old to parse the questions.


Translating source code into a different language as practice

Filed under: Computer Programming, Java Programming — Lorenzo E. Danielsson @ 13:05

One of the things I encourage my programming students to do is to take open source programs and rewriting them in a different programming language, or using a different GUI toolkit. There are a number of benefits to this:

  1. The student learns to read somebody else’s code
  2. The student learns to analyze code in a language that is different from the one they are learning
  3. The student (hopefully) learns a few new programming techniques along the way
  4. It is yet another way to keep the student writing code
  5. It provides a bit of variation from the old “write a program that..”-type exercises.

It’s easy to say that this is a “passive” process, meaning the student simply just translates the code to “their own” programming language without reflecting much about what they are doing. That may be true for some people, but then again, some people go through an entire programming class without reflecting much on what they are doing.

Another thing is that a friend of mine raised the concern that programming languages sometimes differ in techniques and that if I am translating a C program into Java I might be learning “C-isms”. First of all, I don’t quite understand what is so wrong with “C-isms”. Secondly, it is your responsibility as a teacher/mentor to review their code and point out areas where they could improve the program.

Remember that at first the student’s primary concern is with getting the program running at all. It is only once they have been able to do succeed in that that they will start worrying about “making it look like a conventional Java program”. The following might be a rough sketch of this process.

  1. Translate the program straight off (leaving variable names exactly the same etc). At this stage, the students only concern is to get the program to compile (in the case of a compiled language) and run, with all the functionality of the original program intact.
  2. Next they begin to do things like renaming variables to suit the language. For example, if translating a C program to Java, you might want to rename a variable from x_axis to xAxis simply because that is a convention that most Java programmers follow.
  3. Then the student refines the code. In the case of translating from a non-object orient language to an object oriented one, this might involve moving parts of the application functionality out into classes, where that makes sense.

Translating a program from for example C to Java, or from using Qt to using Gtk is not some form of miracle solution that will turn everybody into a master programmer. But it is a way to let the people who are genuinely interested in programming to get some extra practice. That’s all. I find the exercise useful. I would love to hear what others think. Please leave your comments/experiences in the comments section.

Finally I will give a small example. Recently, I had a Java student who said he wanted to learn how to do graphics programming. So I helped him get a hold of some programs (mostly in C) and told him to start translating them into Java. To demonstrate it I took this program by CorTeX/Optimum and wrote it as a Java applet. You can see the result below (you will obviously need to create an HTML document to load the applet in order to see it in action).

  1 /*
  2  * "Flashouillis" for Java.
  3  *
  4  * Original C program written by corTeX/Optimum.
  5  *
  6  * Author: Lorenzo E. Danielsson <danielsson.lorenzo (AT) gmail DOT com>
  7  * Date created: 2007.04.21
  8  */
 10 import java.awt.Color;
 11 import java.awt.Graphics;
 12 import java.awt.Image;
 13 import javax.swing.JApplet;
 15 import static java.lang.Math.cos;
 16 import static java.lang.Math.sin;
 17 import static java.lang.Math.random;
 19 public class JFlash extends JApplet implements Runnable {
 20     private final int WIDTH = 500;
 21     private final int HEIGHT = 500;
 22     private final int DELAY = 10;
 23     private final int FLASH_MAX = 5000;         // Number of points.
 24     private final int G_ACC = 330;              // Acceleration (g).
 26     private Thread animation = null;            // Animation thread.
 27     private Graphics buffer = null;             // Back buffer for drawing.
 28     private Image image = null;
 29     private Flash[] flash = new Flash[FLASH_MAX];
 30     private int current;
 31     private float ax = 0.0F, ay = 0.0F, az = 0.0F;
 33     public void init() {
 34         image = createImage(WIDTH, HEIGHT);
 35         buffer = image.getGraphics();
 37         for (int i = 0; i < FLASH_MAX; ++i) {
 38             flash[i] = new Flash();
 39             flash[i].state = 0.0F;
 40         }
 42         current = 0;
 43     }
 45     public void paint(Graphics g) {
 46         buffer.setColor(Color.BLACK);
 47         buffer.fillRect(0, 0, WIDTH, HEIGHT);
 49         for (int i = 0; i < FLASH_MAX; ++i) {
 50             if (flash[i].state == 0 || flash[i].state >= 1)
 51                 continue;
 53             int x = (int)(flash[i].x + flash[i].vx * flash[i].state);
 54             int y = (int)(flash[i].y + flash[i].vy * flash[i].state
 55                     + (flash[i].state * flash[i].state) * G_ACC);
 57             if (x < 0 || x > WIDTH || y < 0 || y > HEIGHT)
 58                 continue;
 60             int red = (int)(flash[i].r * (1 - flash[i].state)) << 3;
 61             int green = (int)(flash[i].g * (1 - flash[i].state)) << 2;
 62             int blue = (int)(flash[i].b * (1 - flash[i].state)) << 3;
 64             if (red > 255) flash[i].r = 255;
 65             if (green > 255) flash[i].g = 255;
 66             if (blue > 255) flash[i].b = 255;
 68             buffer.setColor(new Color(red, green, blue));
 69             buffer.drawLine(x, y, x, y);
 71             flash[i].state += 0.007F;
 72         }
 74         g.drawImage(image, 0, 0, null);
 75     }
 77     public void run() {
 78         Thread thread = Thread.currentThread();
 79         while (animation == thread) {
 80             repaint();
 82             int x = (int)(WIDTH/2 + WIDTH/4 * (cos(ax+ay) + sin(ay-az)));
 83             int y = (int)(HEIGHT/2 + HEIGHT/4 * (sin(ax-ay+2*az)
 84                         + sin(ax+ax/2)));
 86             for (int j = 0; j < 40; ++j) {
 87                 float rd = (float)(2.0 * random() * Math.PI);
 88                 float vx = (float)(cos(rd));
 89                 float vy = (float)(sin(rd));
 90                 rd = (float)(50.0 + random() * 30.0);
 91                 vx *= rd;
 92                 vy *= rd;
 94                 flash[current].x = x + ((int)(random() * Integer.MAX_VALUE)
 95                         & 3);
 96                 flash[current].y = y + ((int)(random() * Integer.MAX_VALUE)
 97                         & 3);
 99                 flash[current].vx = vx;
100                 flash[current].vy = vy;
101                 flash[current].state = 0.01F;
103                 flash[current].r = (int)(10 * cos(ax*6) + 20);
104                 flash[current].g = (int)(20 * cos(ay*5) + 40);
105                 flash[current].b = (int)(10 * cos(az*7) + 20);
107                 ++current;
108                 if (current == FLASH_MAX)
109                     current = 0;
110             }
112             ax += 0.05F;
113             ay += 0.03F;
114             az += 0.0441F;
116             try {
117                 thread.sleep(DELAY);
118             } catch (Exception e) {}
119         }
120     }
122     public void start() {
123         animation = new Thread(this);
124         if (animation != null)
125             animation.start();
126     }
128     public void stop() {
129         if (animation != null)
130             animation = null;
131     }
133     public void update(Graphics g) {
134         g.clipRect(0, 0, WIDTH, HEIGHT);
135         paint(g);
136     }
137 }
139 class Flash {
140     public int x = 0, y = 0;
141     public int r = 0, g = 0, b = 0;
142     public float state = 0.0F;
143     public float vx = 0.0F, vy = 0.0F;
144 }

So this obviously does quite a few things that look familiar to a C programmer but maybe less so to a person from a Java background. But the point is that Java does support the shift operators. I’m not sure if you gain anything performance-wise in Java by using the shift operators for multiplying and dividing, but it is not illegal to do so.

Now this is just a first iteration of the program. It works, and looks like the original when run. You could easily modify it to look “better” from a Java point of view.


Understanding algorithms for novice programmers

Filed under: Algorithms, Computer Programming — Lorenzo E. Danielsson @ 19:12

Q: what two tools are essential for a novice programmer trying to understand how algorithms work?
A: pen and paper.

I think that one of the major hurdles for novice programmers comes when they have managed to grasp the syntax of a programming language and move on to actually trying to do something with the language. That is when the concept of algorithms comes in. The first step for the programmer is to learn about existing algorithms and to try to understand them. Already here many people start to find difficulties.

In the old days, when much of the world was ruled by the Emperor of Rome and I was learning how to program, we were encouraged to always work through algorithms on a piece of paper. Going through the algorithm step by step really helps in understanding what the code does. So my usual advice to new programmers is this: always work through parts of the code that you don’t understand on paper. If you still don’t understand the code, go through it again, and again, until you understand exactly what is happening.

Very few people seem to listen to this advice (I guess it is more fun to write code, even if you are just copying it off a web site). The people who don’t often come back to me later to tell me that they find programming difficult. Well, if you want learn how to swim, you really have to jump into the water. If somebody tells you this, and you don’t listen, can you then blame the water for the fact that you cannot swim?

Let’s look at a simple example: bubble sort. It is not the best of sorting routines, but it is, or at least was, the first sorting algorithm that most people learn. It’s also trivial so it makes a good example. Below is a simple implementation of bubble sort, written in C (the language is unimportant, I could have given the example in Pascal and the principle would still have been the same).

 1 #include <stdio.h>
 3 #define ARRAYLEN 10
 5 int main(int argc, char **argv)
 6 {
 7     int nums[] = { 7, 2, 6, 10, 1, 9, 5, 8, 4, 3 };
 8     int i, j, tmp;
10     for (i = 0; i < ARRAYLEN-1; ++i) {
11         for (j = i+1; j < ARRAYLEN; ++j) {
12             if (nums[i] > nums[j]) {
13                 tmp = nums[i];
14                 nums[i] = nums[j];
15                 nums[j] = tmp;
16             }
17         }
18     }
20     for (i = 0; i < ARRAYLEN; ++i)
21         printf("%dn", nums[i]);
23     return 0;
24 }

Anybody who has even the slightest programming experience should be able to follow what the code does, from a syntactical point of view. But let’s try to understand what the code does, that is, what results are produced. So go and grab a notebook and a pen.

The lines 10-18 are where the integers are sorted. This is the part of the code that we need to analyze. First of all, draw a small table, two rows and ten columns. You will draw this again, several times. In the first row you write down the index values of the array. That would be 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9. In the second row you fill in the number that occupies each array element at the start of the program. Now you have your start condition.

During the course of the program the integers in the array will be thrown around until finally they are sorted from the lowest number to the highest. Now you want to understand why that happens. We can see that we have an iterator, i, that loops through the values 0 to the second-to-last element of the array. On your paper, jot down that i is 0 (zero).

Next we have an inner loop where the iterator j loops through the values i+1 up to the last element of the array. On your piece of paper, write down that j is 1.

The next code block compares the value held in nums[i] with that of nums[j]. In the first iteration of both loops, that means we are comparing the value of nums[0] with that of nums[1] (look at your paper and you should see i = 0, j = 1 there). The values of these are 7 for nums[0] and 2 for nums[1]. Since 7 is larger than 2 the if statement evaluates to true and its code block is executed.

What happens in the code block is that two variables, nums[0] and nums[1] exchange values. In order to do that we proceed as follows: 1. copy the value of nums[0] to a temporary variable, 2. copy the value of nums[1] to nums[0], 3. copy the old value of nums[0] to nums[1]. In step 2 we overwrite the value of nums[0], that is why we need to store it away to a temporary variable.

What has happened is the first two array elements have swapped values. So draw the array table once more. This time array element 0 should hold the number 2, and array element 1 should hold the number 7.

The next thing that will happen is that j will be incremented by 1 (i will only be incremented once the inner loop completes). Check if the control condition is still true. It is. The value of j is now 2, and the control condition states that the loop should continue as long as j is less than ten.

The value of nums[0] (which is now 2) will now be compared to that of nums[2] (6). This time, 2 is less than 6, so the if statement evaluates to false. We increase j by one and check if the loop condition is true. The program continues like this until j has reached 10. Then the inner loop completes.

If you have been following along with your pen and paper through all the steps of your inner loop, then your last array table should contain the number 1 in array position 0. What that means is that after one iteration of the outer loop, the first array position contains the lowest value in the array.

Now it is time to increment i by 1. On your paper you write down that i is now 1. Next we start a new cycle of the inner loop, so you write down j = 2 (i+1) on your paper. For each iteration of the inner loop, we again go through the comparison and swap values if the condition nums[i] > nums[j] is true. If you look at your array table after the second iteration of the outer loop, the first two array elements should contain 1 and 2.

By the time you have gone through the last iteration of the outer loop you will hopefully have gained a good understanding of how the bubble sort algorithm works. Writing it is trivial, copying it from somebody else even more so. But in order to be a programmer you don't need to just be able to type code and get it to run, you need to understand it as well.

Stepping through code in this way also gives you the opportunity to test a few "what ifs". Suppose, for example, you didn't understand why the start value of j should be i+1 and not i. Well, then you could test it. By writing down all the values and comparisons that are done step-by-step you will soon see that that would introduce a redundant comparison when a value is compared with itself.

You may notice that it takes quite a bit of time to analyze a piece of code in this way. But it's well worth it, especially when you apply the principle to more complex algorithms where it is not so apparent what the code does. And remember, in order to learn programming (or any other skill for that matter), you must be ready to sacrifice some time and effort.

Blog at