deliveredtechnologies/rulebook

Allow Passing A Function For Default Result Type

Kurry opened this issue · 1 comments

Kurry commented

It would be nice to be able to pass a function to the method withDefaultResult, that way you can construct the default result using the rule book argument type. How I'm using the rule book is to construct an object, given a set of rules.

This is what I currently have:

        RuleBook<TradeRecommendation> ruleBook = RuleBookBuilder
                .create(BrokerRuleBook.class)
                .withResultType(TradeRecommendation.class)
                .withDefaultResult(null)
                .build();
        // create default result
        addRule(RuleBuilder.create()
                .withFactType(OrderSequenceMap.class)
                .withResultType(TradeRecommendation.class)
                .when(o -> true)
                .then((facts, result) -> {
                    TradeRecommendation trade = new TradeRecommendation();
                    trade.side = facts.getOne().side;
                    trade.amount = facts.getOne().amount;
                    trade.security = facts.getOne().ticker;
                    result.setValue(trade);
                })
                .build());

What I would like to do is:

        RuleBook<TradeRecommendation> ruleBook = RuleBookBuilder
                .create(BrokerRuleBook.class)
                .withResultType(TradeRecommendation.class)
                .withDefaultResult(order -> {
                    TradeRecommendation trade = new TradeRecommendation();
                    trade.side = order.side;
                    trade.amount = order.amount;
                    trade.security = order.ticker;
                    return trade;
                 })
                .build();

You can just omit the 'when' in the builder.

Based on what you are trying to do, something like this should work:

RuleBook<TradeRecommendation> ruleBook = RuleBookBuilder
    .create(BrokerRuleBook.class)
    .withResultType(TradeRecommendation.class)
    .addRule(rule -> rule
        .withFactType(OrderSequenceMap.class)
        .then((facts, result) -> {
            TradeRecommendation trade = new TradeRecommendation();
            trade.side = facts.getOne().side;
            trade.amount = facts.getOne().amount;
            trade.security = facts.getOne().ticker;
            result.setValue(trade);
        })
       .build();

I haven't actually run it yet, but it should work. And I think it looks pretty close to what you are asking for, no?

I'll validate it by running sometime tomorrow.
Apologies for the delayed response.