Monday, April 24, 2006

What's Wrong With This Statement?

Code in a textbox valid method:

IF TRIM(THIS.Value)<>TRIM(THIS.oObject.SavedValue)
THIS.oObject.SavedValue = TRIM(THIS.Value)
ENDIF


On the surface, this code may look like it should execute properly, right?

There is one approach that you might change immediately :

Sethe ControlSource property to THIS.oObject.SavedValue. This would remove the need for this code completely.

But is there anything else wrong with the statement?

When you look at the value of an object and compare it to something, it's easy to get into the habit of only changing the initial value. If THIS.Value isn't empty, then you're going to do something but in the case of the statement above, what about the comparing value? (the one stored in THIS.oObject.SavedValue)

IF "Andrew"<>"andrew"
** This code will execute
ENDIF

IF "Andrew"<>""
** This code will NEVER execute
ENDIF

As a result, the original code (that updated the value) would never execute.

A small but good thing to look for on code reviews, especially when trying to find out why code in FoxPro isn't working the way you expect it to.

1 comment:

Ryan Katri said...

This is why I never use <> when comparing for string inequality. Rather, I always write it like this:

!(value1 == value2)