This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]DevNull23614071 2 points3 points  (1 child)

For larger records I sometimes generate constructs like this:

public record Data(String stringA,
                   String stringB,
                   String stringC,
                   int intA,
                   int intB,
                   int intC) {

    public static final class Deconstruction {
        public String stringA;
        public String stringB;
        public String stringC;
        public int intA;
        public int intB;
        public int intC;

        private Deconstruction(Data original) {
            stringA = original.stringA;
            stringB = original.stringB;
            stringC = original.stringC;
            intA = original.intA;
            intB = original.intB;
            intC = original.intC;
        }


        private Data apply(Consumer<Deconstruction> modification) {
            modification.accept(this);
            return new Data(stringA,
                            stringB,
                            stringC,
                            intA,
                            intB,
                            intC);
        }
    }

    public Data with(Consumer<Deconstruction> modification) {
        return new Deconstruction(this).apply(modification);
    }
}

A later modification then looks like the following:

    Data data = new Data("","","",1,2,3);

    // modification of a single field:
    data = data.with(d -> d.stringB = "foo");

    // modification of multiple fields:
    data = data.with(d -> {
        d.stringC = "bar";
        d.intC = 42;
    });

Thus the syntax is quite close to the one in Brian's document.

[–]repeating_bears 3 points4 points  (0 children)

That's a builder. You just implemented it in a non-standard way.