Yet another question about reusable functions

Hi Rich / @rlkoshak and everybody else,

I plan to “modularize” my rules by creating reusable functions. I have seen and read Creating Your Own Library in the documentation, however, I like to know what you think about this approach:

  • Storing the function as usual as a script
  • The main script calls the “function script” by
rules.runRule(uid, {'parameter1': 'value'});
  • and gets the return value of the function script through a shared cache variable

I thought about the downside of this approach:

  • maybe a timing issue if the shared cache variable is getting created after rules.Runrule() is finished?
  • If the function script returns early because of an error and the return value (cache variable) already exists because of an earlier call (could be minimized by explicitly deleting the shared cache variable by the main script)
  • if the function script is called almost simultaneously by two different scripts the shared cache variable could only be created once (solution would be to prefix the return value by a unique prefix (like ruleUID of the main script)

But I can’t see any major obstacles. What is your opinion?

There are limitations to that approach that you will quickly run into and realize it’s not the best.

Problems include:

  1. no return value, using the cache is kind of hackey
  2. Using the shared cache is problematic and not supported for JS Objects, only primitives and Java Objects
  3. if two rules call the same rule at the same time you’ll get a Multi-threaded exception
  4. if two rules try to access the same Object from the cache at the same time and it is a JS Object you’ll get the Multi-threaded exception.

Rules calling rules is not a replacement for building a real library of reusable functions.

1 Like