Notes from porting Java code to .NET
Recently I needed to use a DFA/NFA (finite-state automata) implementation from
a Java package in .NET. I could not find a port of this particular
package, and
IKVMC was not an option since I preferred
to depend only on the standard library (BCL). So, I decided to port the code
myself.
In my case, the Java package didn’t have unit tests (at least not publicly
available on the website). How could I know that the results of the ported
code are the same as those of the original code?
The solution I came up with was the following:
- Write integration tests, one for the ported code and one for the Java code.
- Both tests should have the same, deterministic, input.
- Keep porting enough code from the Java source in order to make the test pass.
- Verify that results are the same as with the test in Java.
- Recursively repeat this process until all tests pass and yield correct
results.
An example can be found here with integration tests for
ported
code and
Java
(through IKVMC).
During the process of porting I came across a few differences between Java
and .NET, particularly:
- Multi-dimensional array syntax is slightly different.
- Substring method parameters have a different meaning.
- In C# we pass StartIndex, Length.
- In Java we pass StartIndex, EndIndex.
- In Java, the list and set implementations override equals, etc. The
equivalent doesn’t happen in .NET.
- The Java LinkedList Add method appends the specified element to the end of
the list. The equivalent in .NET is the AddLast method.
- The Java LinkedList Remove(int) method removes the element at the specified
position in the list and returns the element that was removed from the list.
The equivalent in .NET exists only with the use of an extension method.
References
Stack Overflow
Java SE 6 Documentation