To apply as a writer on this blog, Email me on [email protected] OR [email protected]

Friday, January 7, 2011

Language Transition Bugs

There are are subtle differences between languages like C, C++, Java and C#. Programmers transitioning from one language to another should beware of such differences.
As we can see, there are many pitfalls when you think in one language and speak in another. Similarly, when you have considerable experience programming in one language, and start programming in another new language, there are numerous pitfalls associated with that transition. Languages like C++, Java, and C# are closely related, because they inherit a lot from C. The code segments that have similar syntax can have subtly different semantics, and transitioning between these languages can cause BUGS. A very good example is the ~ symbol use for destructors in C++ and C# : the syntax and name of the feature (destructor) is the same, but there is a subtle difference. In C++, destructors are deterministic, whereas in C#, destructors are non-deterministic. C++ programmers who are new to C# can introduce bugs if they assume the deterministic behaviour of destructors while coding in C#. So let"s look at some actual code segments illustrating such language transition bugs. Specifically, we"ll focus on Java and C# differences. Here is our first code segment:
Well, your first question is sure to be, "Does it really compile?" The answer is: "It depends!" In C#, you'll get a compiler error for attempting to convert a null to an int . But you"ll be really surprised that in Java, it compiles, but fails with a NullPointerException during execution. The code compiles in Java because of some arcane language rules on boxing and un-boxing. Now, how about the following code? If u r a Java programmer, you would say the code returns true; if u r a C# programmer, you would say false !
In C#, boxing a primitive type to a reference type causes the creation of two different reference type objects, and hence the condition check will return false. In Java, boxing a primitive type to a reference type reuses the existing boxed object, and hence it"s true !!! Here is the last example: Now, what"s the value of b3 ? It"s 128 for a C# programmer and -127 for a Java programmer! In C#, a byte is unsigned, so the range is from 0 to 255; in Java, a byte is signed, so the range is from -127 to +128 ! by - geniusRK

2 Visitor Reactions & Comments:

Amarjit Singh said...

A very nice & basic article on softwares bugs.

geniusRK said...

thanx bro !!! :)