Skip to content

[Java] safer method for decoding repeating groups #891

@spoerri

Description

@spoerri

Would you accept a PR to generate an additional method to make it safer to decode repeating groups?

By safer, I mostly mean preventing accidentally not completely decoding a group, or otherwise messing up the required order of invocation.

For CarDecoder it might be used like:

carDecoder.decodeGroups(
    (count) -> newEncoder.newMpgEncoder(count),
    (newMpgEncoder, fuelFiguresDecoder) -> newMpgEncoder.next().mpg(fuelFiguresDecoder.mpg()),
    IGNORE_A_COUNT,
    IGNORE_A_GROUP
);

And the generated code would be like:

public <R> void decodeGroups(
    IntFunction<R> fuelFiguresInit,
    BiConsumer<R, FuelFiguresDecoder> fuelFiguresConsumer,
    IntFunction<R> performanceFiguresInit,
    BiConsumer<R, PerformanceFiguresDecoder> performanceFiguresConsumer)
{
        FuelFiguresDecoder fuelFigures = fuelFigures();
        BiConsumer<R, FuelFiguresDecoder> fuelFiguresConsumer = fuelFiguresInit.apply(fuelFigures.count());
        while (fuelFigures.hasNext())
        {
            fuelFiguresConsumer.accept(consumer, fuelFigures.next());
        }

        PerformanceFiguresDecoder performanceFigures = performanceFigures();
        BiConsumer<R, PerformanceFiguresDecoder> performanceFiguresConsumer = performanceFiguresInit.apply(performanceFigures.count());
        while (performanceFigures.hasNext())
        {
            performanceFiguresConsumer.accept(performanceFiguresConsumer, performanceFigures.next());
        }
}

//of course next bit need not be generated for each decoder:
public static final IntFunction IGNORE_A_COUNT = i -> null;
public static final BiConsumer IGNORE_A_GROUP = (x,y) -> {};

I understand this would involve breaking compilation if a new group is added to the schema without an accompanying code change. If that's undesirable, we could instead use a "fluent" approach, in which each method returns something that only has the next appropriate method. The disadvantage of that approach would be needing an extra interface (or class) for each repeating group. If there's any interest, I could give more detail about how that might look...

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions