Monday, June 27, 2011

Servoy TIP: How To Reference A Relation in Code

OK - here's the first Servoy QuickTip - and it has to do with relations. When you're using relations in a conditional statement - and especially when you're using them in calculations - make sure you test for the existence of the relation first.


First - the wrong way:
if(myRelation.getSize() > 0) {
  //do something
}
If you leave the code like this - and the relation is invalid for the current record - Servoy will complain. The above code is saying "IF the number of related records > 0, THEN do something." However, if the relationship is invalid - then Servoy will throw an "invalid" error. You should always check and make sure the relation is valid before you try to access any of the functions on a relation.

The right way:
if(myRelation && myRelation.getSize() > 0) {
  //do something
}
We've subtly changed the question to "IF the relation is valid and the number of related records > 0 THEN do something."

Another way to say the same thing would be to ask the question: "What color is your sister's hair?" when someone only has brothers. Their answer is going to be "I have no sister." (error!). So, you should ask the question: "If you have a sister, what color is her hair?"

CORRESPONDING VIDEO

2 comments:

  1. What about databaseManager.hasRecords(myRelation)?

    ReplyDelete
  2. Yes! Also a very good way to do it (I always forget about that one!)... great tip!

    ReplyDelete