Wednesday, February 18, 2009

Mysterious validation function.

Making changes to some application and having some problems with validation, I came across this validation function:

public new bool Validate(bool someParameter)
{
bool blnResult = true;

if (name != null)
{
if (!name.Validate())
blnResult = false;
}

if (address != null)
{
if (!address.Validate(someParameter))
blnResult = false;
}

if (somethingElse != null)
{
if (!somethingElse.Validate())
blnResult = false;
}

if (someMore != null)
{
if (!someMore.Validate())
blnResult = false;
}

return blnResult;
}

So I asked myself, why would this function go through all validations each time even if it knows after the very first one that the blnResult is false and that will not change?

After some thought and investigation, the most likely answer is that the application was growing little by little. So, whenever its functionality was extended, say, from just keeping names to keeping names and addresses, the person currently in charge of the application would just copy and paste this bit

if (name != null)
{
if (!name.Validate())
return false;
}

replace name with address and move on.

After I made some small change, the function does not look much different, but I have much less troubles with validation now.

public new bool Validate(bool someParameter)
{
if (name != null)
{
if (!name.Validate())
return false;
}

if (address != null)
{
if (!address.Validate(someParameter))
return false;
}

if (somethingElse != null)
{
if (!somethingElse.Validate())
return false;
}

if (someMore != null)
{
if (!someMore.Validate())
return false;
}

return true;
}
by . Also posted on my website

No comments: