mercredi 23 mai 2012

cryptic perl

"Perl is the only language that looks the same before and after RSA encryption."
Keith Bostic. Programmer, created Sleepycat, contributed to free BSD unices.

Funny C quote

"One of the main causes of the fall of the Roman Empire was that, lacking zero, they had no way to indicate successful termination of their C programs."
Robert Firth. Author of programming books.

lundi 21 mai 2012

one of a million reasons to love programming

From the introduction to the excellent free book Programming ground up,

I love programming. I enjoy the challenge to not only make a working program, but to do so with style. Programming is like poetry. It conveys a message, not only to the computer, but to those who modify and use your program. With a program, you build your own world with your own rules. You create your world according to your conception of both the problem and the solution. Masterful programmers create worlds with programs that are clear and succinct, much like a poem or essay.

vendredi 6 avril 2012

Swapping numbers in java, pass-by-value VS pass-by-reference

I never thought about it, but I just discovered it is not possible to write a method to swap numbers in Java since Java is strictly pass-by-value, not pass by reference.
public void swapNumbers(int x, int y)
{
    int temp = x;
     x = y;
     y = temp;
}
If we call this function to try to swap numbers, the numbers won't be changed.
There is an example of swapping numbers in this link: http://www.roseindia.net/java/beginners/swapping.shtml, but it's confusing for beginners.

public class Swapping{
  static void swap(int i,int j){
  int temp=i;
  i=j;
  j=temp;
  System.out.println("After swapping i = " + i + " j = " + j);
  }
  public static void main(String[] args){
  int i=1;
  int j=2;
 
  System.out.prinln("Before swapping i="+i+" j="+j);
  
swap(i,j);
 
  
}
}


This example doesn't mention that after we call the method swap, the numbers will return to their original values after this call.
The same operation is really simple in C++ which allows us to pass values by reference

void swapNumbers(double& a, double& b)
{
    double temp = a;
    a = b;
    b = temp;
}
 
Now, when we call this function, a and b will be swapped.*

double number1(5.5), number2(7.0)
swapNumbers(number1, number2);
cout << "First number : << number1 << endl;
cout << " Second number :" << number2 << endl;

The output will be
First number : 7.0
Second number 5.5;

A reference is merely an alias, another name for the same variable. Hence, making operations on a variable will also change the variable value.

real life example for passing argument by reference in java

I read this in one of the comments for this answer in SO http://stackoverflow.com/a/40523/612920

My attempt at a good way to visualize object passing: Imagine a balloon.
Calling a function is like tieing a second string to the balloon and handing the line to the function.
parameter = new Balloon(); will cut that string and create a new balloon (but this has no effect on the original balloon).
parameter.pop(); will still pop it though because it follows the string to the same, original balloon. Java is pass by value, but the value passed is not deep, it is at the highest level, i.e. a primitive or a pointer. Don't confuse that with a deep pass-by-value where the object is entirely cloned and passed.

mercredi 4 avril 2012

Everyone should learn Vi / VIm

I always wanted to learn vi. It seems that once you get to know it well, you can be a lot more productive.
The problem is you got to invest some time to learn all the shortcuts that will help you to be productive and practice them often to get used to them. A good start is the vimtutor which is an interactive learning resource that can be started by typing vimtutor in the shell. Once you finish the tutorial, you can find a ton of resources on the internet. Personally, I'm starting with vim tips http://vim.wikia.com/wiki/Vim_Tips_Wiki. There is a lot of good tips, like autocompletion feature which can be done using Ctrl+N for next word and Ctrl+p for previous word.
If I can be as good in vi as this guy http://stackoverflow.com/a/1220118/612920 , I'm sure I'll be at least 10 times faster. If you decide as well to start learning vim, I'm sure you are making a good decision.

vendredi 20 janvier 2012

Getting started with TDD - Test Driven Development

Update: Here is the GitHub repository containing a FlashBuilder project containing the final test:
Flex-HashMap

I am just familiar with some basic concepts of unit testing. I didn't have the chance to work in a professional environment that would allow me to write unit tests for complicated business code, so all I've tried is really simple examples like the famous addition example. In this article, I'm trying to get a little bit more in depth by using TDD (Test Driven Development).
Test Driven Development can be defined as reversing the traditional development life-cycle upside down. Instead of writing the tests after our code is ready to be tested, the first thing we do is to write tests even before we have any code to test. The code is written for the sole purpose of making tests pass. So the development life-cycle is as follows:
- add a test
- make sure that the test fails
- write the simplest code to make the test pass
- refractor
- do it again
as simple as that. The benefits for using TDD come from the fact that we are repeating very short development life-cycles, and as a result we end up having a high quality and error prone code. I'm implementing the unit tests for a HashMap class implemented in AS3 By Eric J. Feminella. You can find the final code here :
Eric J. Feminella HashMap Implementation. Though, I will be making some changes to it later, I'll put the final code on github.
Of course, in TDD, we have to begin by writing the tests, so before implementing that class, we need to implement a test class:

package tn.zuro.tests.collections
{
    public class HashMapTest
    {        
        private var map:IMap;

        [Before]
        public function setUp():void
        {
            map = new HashMap();
        }
        [After]
        public function tearDown():void
        {
        }
    }
}

Here is our first failing test. A test that doesn't compile can be considered as a failing test. Our test won't compile here since the compiler won't recognize neither IMap or HashMap as we have not implemented them yet. Now let's write some code to make this test pass or at least compile.

package tn.zuro.collections
{
    public interface IMap
    {
    }
}

package tn.zuro.collections
{
    public interface HashMap
    {
    }
}
Now our code will compile, but it still fails: we haven't implemented any runnable methods yet. Let's start by adding some basic methods. The HashMap in our case will use flash.utils.Dictionary since it allows us to implement key/value pairs. we could start by implementing a test method for the method put:
[Test]
public function testPut():void
{
    map.put("d", "value A");
    map.put("e", "value B");
    map.put("f", "value C");
    map.put("u", "value X");
    map.put("v", "value Y");
    map.put("w", "value Z");
}
Now if we run the test, it will fail, the method is not implemented. We go back to IMap, and we add the put method declaration:
function put(key:*, value:*) : void;

Now we need to implement the simplest possible code to make the test pass:
public function put(key:*, value:*) : void
{
    _map[key] = value;
}
Finally, we have a test that passes without problems. Our first iteration is complete, now we have to repeat. We will test the size method next, so that we can add some assertions to our code:
[Test]
public function testSize():void
{
    assertEquals(map.size(), 6);
    map.put("d", "value D");
    assertEquals(map.size(), 7);
    map.put("a", "value K");
    assertEquals(map.size(), 7);
}
We can also add some code to the setUp method, so that we have some key/value pairs in our hashmap to play with.
private var map:IMap;
[Before]
public function setUp():void
{
    map = new HashMap();
    map.put("a", "value A");
    map.put("b", "value B");
    map.put("c", "value C");
    map.put("x", "value X");
    map.put("y", "value Y");
    map.put("z", "value Z");
}
The test fails again, since the method size doesn't exist, yet. Thus, we declare it in the interface and implement it in the HashMap class:
function size() : int;
        
public function size() : int
{
    var length:int = 0;
    for ( var key:* in _map )
    {
        length++;
    }
    return length;
}
The loop
for (var key:* in _map)
allows us to iterate over the keys of the dictionary, to iterate over the values, we can use a for each loop. Now our test passes again, and we can see the results of our assertions. In the method testSize, we have the following assertions:
assertEquals(map.size(), 6);
which should return true since we have put 6 values in the setUp method. We are also sure that the put method works the way it should be.
assertEquals(map.size(), 7);
returns true for the same reasons
and then:
    map.put("a", "value K");
    assertEquals(map.size(), 7);
    this returns true as well, because we used the same key again, so we have
_map["a"] = "value K";
which updates the value associated with the key "a".
   
Let's repeat one more time to make sure we got the process right, and to understand how useful tests can be.
I'm going to add a test for the clear method which will remove all the elements from the dictionary. The clear method will use another method which will remove a key/value pair from the dictionary. We should start by adding a testRemove method to have a failing test, make the test pass, and repeat again. We skipped the refractoring step here, cause the code is too simple and does not require any refractoring. Then we repeat again. Then we write a test for the clear method.
[Test]
public function testRemove():void
{
    map.remove("a");
    assertEquals(map.size(), 5);
}
        
[Test]
public function testClear():void
{
    map.clear();
    assertEquals(map.size(), 0);
}
IMap.as
function remove(key:*) : void;
function clear() : void;
HashMap.as
public function remove(key:*) : void
{
    _map[ key ] = undefined;
    delete _map[ key ];
}
        
public function clear() : void
{
    for ( var key:* in _map )
    {
        remove( key );
    }
}
Now that all the code of the two iterations is in place, everything should be working smoothly, right? Well, not quite. The test method testClear is going to fail. This means that there is a problem with the clear function. The problem comes from the first instruction in the remove function. 
_map[key] = undefined;
I managed to find the problem after I asked a question in StackOverflow: Flex dictionary question. If we didn't test this code thouroghly, it's possible we wouldn't notice this error. And using TDD, we noticed it very early in the development lifecycle, so that it could be corrected very early, and now we have less bugs to worry about. The remove function should look like this:
public function remove(key:*) : void
{
    delete _map[ key ];
}
And this time, the tests pass. I guess that's all what's TDD is about. It's not complicated. It just takes a little time to get used to it, and once we know it good enough, it can speed up development significantly.