wiki:Doc/panc/tips

Record Validation

Often one wants to ensure that several entries in a record are consistent. For example, here one wants to ensure that the number of children is consistent with the given maximum. To remember where to put the validation code, keep in mind that you're validating the record and not the entries of the record. Thus, the 'with' clause should be tied to the record definition.

type my_kids = {
  'children' : string[1..] with is_profile_list(SELF)
  'maxchildren' ? long(1..)
} with {
  if (exists(SELF['maxchildren'])) {
    SELF['maxchildren'] >= length(SELF['children']);
  } else {
    true;
  };
};

For the older compiler (v6) does not allow a 'with' clause to be put on a record definition. For that compiler, you must define an intermediate type.

type my_kids = {
  'children' : string[1..] with is_profile_list(self)
  'maxchildren' ? long(1..)
};

type my_validated_kids =
  my_kids with {
    if (exists(self['maxchildren'])) {
      self['maxchildren'] >= length(self['children']);
    } else {
      true;
    };
  };

This same technique can be used with any resource (list, nlist, record).

Do not copy SELF

Sometimes we do:

"/my/path" = {
   temp = SELF;
   # Operations with temp
   temp["foo"] = "bar";
   temp;
};

This forces a copy of SELF and then assigns back to the path. The following alternative is more efficient in speed and memory:

"/my/path" = {
    SELF["foo"] = "bar";
    SELF;
};
Last modified 14 years ago Last modified on Aug 27, 2010, 2:32:39 PM