Thursday, April 5, 2012

int and short compatibility problem, not a versioning problem. it's a bad design decision

On my last post about int compatibility problem, I have an impression that the problem lies in the versioning problem.

On C# and C++, following would compile, but not in Java:

class Alien
{
 String invade(short ships) { return "int"; }
}


public class Invader
{
 public static void main(String[] args)
 {
  System.out.println(new Alien().invade(7));
 }
}


If it really is about versioning problem, why Java allows mapping numbers to float?


Java would compile this:

class Alien
{
        String invade(float ships) { return "float"; }
}

public class Invader
{
        public static void main(String[] args)
        {
                System.out.println(new Alien().invade(7));
        }
}

Now if you put Alien class and Invader class to their own file, the mappability of number to float shall have a versioning problem:

Alien.java:
class Alien
{
 String invade(float ships) { return "float"; }
}

Invader.java:
public class Invader
{
    public static void main(String[] args)
    {
        System.out.println(new Alien().invade(7));
    }
}

Compile both files, then run it, output will be:
float

Now try to modify the Alien.java and then re-compile it (note: don't re-compile Invade.java):

class Alien
{
 String invade(float ships) { return "float"; }
 String invade(int ships) { return "int"; }
}

Then re-run Invader (don't recompile it), output will be:
float

Now that's weird, if you read Invade.java source code, you can see that the number 7 could be mapped to overloaded method with int parameter, but since the burned instruction on the call site is bound to call the method with float parameter, the code would still continue to call the method with float parameter, regardless of the component(Alient.class) having a more compatible method, one that accepts int. To coerce the caller(Invader.class) to sync to the more fitting overloaded method, re-compile the Invader class. Then the output will be:

int


Seeing that a number is compatible to a method that accepts float, why not make it compatible to short then too?

No comments:

Post a Comment