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.

dimanche 18 décembre 2011

Getting started with the javadoc

If you are using eclipse, working with javadoc is pretty easy. It's not that complicated using the command line either, personally I'm an addict to the command line, but I didn't bother too much with generating the javadoc using it since I tried already and I failed miserably. I had a problem when trying to set the classpath, since there was a lot of dependencies to include. I should have written an ant script, but I was too lazy. All programmers are :). So, I just chose the easy way for once, selecting project > generate javadoc... You have then to go through the usual straightforward process, choosing some options and then next, next.

java heap space configuration


And don't forget to configure the JVM heap space, especially when you have a big project with a lot of comments in it. This way, the javadoc will be generated a lot faster, and you won't be at the risk of having an error with heap space.
My advice is, don't forget to document well you code. A good code is a self documenting code. Compare:

int x;
String y;

and

int hitPoints;
String playerName

A lot better, isn't it?
And if you have a self documenting code like the last one, when you put comments to explain it, if you are not going to add some value to the explanation, it's better to leave it as it is.



/** calcualte the number of the likes */ 
public int calculateNumberOfLikes()

That's what I would call a waste of time. Who'd do that anyway, well, more people than you think, not all people have learnt to program the way programming should really be.




/** This function calculates the number of the likes of a friend.
 * 
 * This function calls an FQL query which determines the pages a friend likes,
 * and calculates the number of times he liked an item in that page
 *
 * @author someone 
 */ 
public int calculateNumberOfLikes()

This is just a little example to show the forms a javadoc comment has. The first sentece is a summary of what the function does. Then a more detailed description, then some javadoc-specific tags about the purpose of the function, we can add html tags to this description in order to format it the way we want. There is a lot of tags to know about, which can give us a lot of information about a function, a class or a variable. So, it's good to have the habit of well documenting our code, cause we are not the only ones that work in our code, and we can make others win a lot of time by making it easier for them to understand our code. And in case of a solo programmer working on his hobby project, you'll eventually end up coming back to the code you wrote after some months, and then, there is no telling how much of your code you will remember and how much time you will waste because of a poor documented code.

jeudi 10 novembre 2011

Let's talk about finalize in java

So, what is finalize, how do we use it?
Well, the answer is simple, we don't. To be more precise, most of the time we don't.
The finalize method gets called when an object is garbage collected to clean any mess caused by that object. All java object have that method, since it is implemented on the Object class. And as you are already aware of, it's the mother class of all other java classes. If the object which was just garbage collected, was using system resources, the finalize method will take care of releasing them. An example of these resources could be an open file. So be careful when you try to use it, it won't clean your java objects, it will only take care of non-java resources.

The finalize method shouldn't be used since it's not a very reliable method, since there is no guarantee that the object will be garbage collected during the lifetime of an application, in addition to the fact that it takes care only of non-java resources. But if you want to use it, here's how to proceed.

You have to declare your method this way:

protected void finalize () throws throwable
Now, inside the method:

Since the method is error-prone, it should contain the famous try-catch-finally statement


try
{
    //you do your personalized cleaning operations here
} finally {
    //then you have to call the parent finalize method
    super.finalize()
}
 
Now you have your finalize() method ready for action, just don't forget, don't rely on it too much, because maybe it will be called, and maybe it won't.