Skip to content

Accessor methods in Builders? #234

Description

@jhorsley

I couldn't see a way to have accessors automatically generated in the builder. I have some use cases where I pass a Builder to other methods to set various values and it's helpful for those methods to check existing Builder state. Is this currently possible?

Activity

  1. elucash commented on Jan 11, 2016

    @elucash
    Member

    Thank you for the issue report! We have a solution for that in form of a modifiable companion classes http://immutables.github.io/immutable.html#modifiable . We were trying to not make builders too heavy, and often along with having accessors it is useful so that "builder" could implement abstract value type (things like buildPartial on builder are considered harmful), making modifiable classes more useful for sophisticated building sequences, including copy/clear/reset etc. If you actually want it to be like builder, you can use styles to masquerade modifiable class to have naming conventions of a typical builder

    @Value.Style(
       typeModifiable = "*Builder", // modifiable will be generated as "FooBuilder"
       toImmutable = "build",  // rename "toImmutable" method to "build"
       set = "*", // adjust to your taste: setters with no prefixes like in default builders.
       create = "new", // plain constructor to create builder, just as example
    )  // style could also put on package or as meta annotation
    @Value.Modifiable
    @Value.Immutable
    public abstract class Foo {
       public abstract String getName();
       public abstract List<Integer> getCounts();
       public static FooBuilder builder() {  // just for convenience, can create builder directly
          return new FooBuilder();
       }
    }
    
    FooBuilder builder = Foo.builder()
        .name("Name");
    
    String name = builder.getName();
    boolean nameIsSet = builder.nameIsSet();
    
    Foo foo = builder.build();
    
    // with default styles it would look more like this
    
    ModifiableFoo foo = ModifiableFoo.create()
       .setName("Name");
    String name = foo.getName();
    boolean nameIsSet = foo.nameIsSet();
    ImmutableFoo immutableFoo = foo.toImmutable()
  2. jhorsley commented on Jan 11, 2016

    @jhorsley
    Author

    Nice! Looks like this should do exactly what I need. Many thanks for the super fast reply.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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