Auto Name Suggestion Horror


Recently a Bug was reported in our product about a certain swing window taking a lot of time to appear. Naturally the first thing you do is debug out the issue to find out what is going on behind the scenes that a simple window is taking that long to appear.

As I was stepping through the code using the eclipse debugger i found a call to a method getUniqueName() which was taking a hell of a time to return and the CPU was going mad while I was waiting for the call to return. Inside the method I found this beautifu piece of code that I would like to share with everyone. Here is the master piece:

private String getUniqueName(String baseName, BranchObject newBranch)
{
    String retVal = baseName;
    IBranchLink [] branches = m_javaCommand.getUtilBranches();

    for (int iCheck = 1; iCheck < Integer.MAX_VALUE; iCheck++)
    {
        for (int iBranch = 0; iBranch < branches.length; iBranch++)
        {
            BranchObject branch = (BranchObject)branches[iBranch];
            if ((newBranch != branch) && branch.toString().equals(retVal))
            {
                retVal += iCheck;
            }
            else
            {
                break;
            }
        }
    }
}

The purpose of the code was to search for a unique name to be given to the object that was created wnen the save button was hit on the swing window. For example if the base name is Image then this code will search out the objects to see if there is any object named Image if yes then it tries Image1 and then Image2 until it finds a unique name. Altough the code above doesn’t do this but there is one obvious mistake in the code.

I have fixed the problem but lets see if anyone out there can find the most obvious mistake in the code which was trying was driving the CPU crazy?

Advertisements
Auto Name Suggestion Horror

4 thoughts on “Auto Name Suggestion Horror

  1. The condition should be the one below, no?

    if ((newBranch == branch) && branch.toString().equals(retVal))

    Plus the branch loop should be the outer one and the inner integer loop should only start once the particular branch has been found.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s