[SOLVED] Lambda calling other lambda? (JSR223/JYTHON)

I do this myself sometimes. You are currently chasing a solution to a problem but have you stepped back to ask yourself if there is a way to sidestep the problem entirely with some different approach.

IMHO lambdas are a code smell. They hint that you might be doing something wrong. Lambdas that need to call other lambdas is a code stench. This sort of coding structure is just now well supported by Rules DSL and there are some very serious problems with lambdas including:

  • type errors inside a lambda kills the whole Rule instantly
  • lambdas are not thread safe, if two or more Rules call a lambda at the same time they will stomp on top of each other
  • there is almost always a better way

Not really. Rules DSL is not going to let you structure your code in ways you may be used to if you are already a programmer, it is more than capable of supporting quite complex and robust Rules.

I wouldn’t take it that far. Lambdas for sure are not recommended in most cases. But use of other Java classes or other XTend concepts are absolutely encouraged where they are supported. See Design Pattern: Working with Groups in Rules which is all Xtend stuff you can do in Rules that are absolutely vital.

This is close to the Design Pattern: Separation of Behaviors which is one of the ways to avoid lambdas.

Looking at the code and the sorts of things your lambdas are doing, absolutely rules DSL can handle this but you need to structure it differently. For example, instead of a lambda to calculate if it is after sunset that gets called from multiple rules, use [Deprecated] Design Pattern: Time Of Day to centralize your time calculations and comparisons and in your rules that care about time you just check if(vTimeOfday.state == "EVENING"). You can then trigger rules based on changes to vTimeOfDay. And there is no need for the lambdas.

checkIfAfterSunset gets calculated in the time of day rule, and the two timer lambdas become Rules that get triggered by changes to vTimeOfDay.

At a high level, what you want to do is centralize calculations of states like these into one Rule or set of Rules, store the result in Item(s), and use the Item(s) in your other Rules.

Another approach is to take advantage of Member of Rule triggers, Groups, and Design Pattern: Associated Items to write generic Rules. When all of your lights, for example, are handled by a single Rule, there is no need for lambdas because all the code is there in that one rule.

Having said all that, if you are a programmer already, I second Michael’s recommendation to use JSR223 rules. I find that most programmers can’t or wont try to restructure their code into a more Rules DSL appropriate way and they are much happier in a programming environment they are use to where they have functions and classes and such and are able to use a coding style and structure closer to what they are use to.

1 Like