Saturday, May 15, 2010

Code Cleanup and What It Means

NaroCAD did grow a lot quite a bit as a project. It has a lot of code to play with and in a lot of cases the code was written at different levels of experience and some mistakes were propagated again and again. A simple mistake that NaroCAD codebase has is this:
void SetData(object data)
{
var mouseCoordinate = data as MouseCoordinate;
SetMouseCoordinate(mouseCoordinate.X, mouseCoordinate.Y);
}
If by mistake the method SetData will be called with another class (like a Point3D instance), your runtime error will be a NullPointerException at accessing mouseCoordinate.X (for dereferincing null value).
This code should likely be written as:
void SetData(object data)
{
var mouseCoordinate = (MouseCoordinate)data;
SetMouseCoordinate(mouseCoordinate.X, mouseCoordinate.Y);
}
where conversion is explicit. In this way the exception will be more explicit (that will state about invalid conversion) and the code will be more compact.
How can be done those changes right? Probably there is no simple way, but I've used a tool to discover them. From the total around 5000 introspection errors (like previous one), I've reduced to around 2500 ones, but keep in mind that not all code is NaroCAD code, and some external components cannot be fixed that easy and fixing them will bring no code quality to NaroCAD project itself. Also, as any tool that do automatically scan, it give false positives (for example the reflection solved methods are in many cases detected as "unused", but in fact they are used directly by their name - in case of events or of Lua script commands) so this will mean that at the end most execution crashes will give more sense.

One last note is that for some reason Visual Studio 2008 Standard (not Pro) gave an error of invalid project file at some test unit assemblies. I've regenerated them creating by hand the same project in VS Standard and seem to work. In this way those folks which use Standard version because is lowcost and do not want to use Pro version or SharpDevelop (an opensource C# IDE), can build also the test units for solver component and application framework.

No comments: