inferred / FreeBuilder

Automatic generation of the Builder pattern for Java
Apache License 2.0
838 stars 101 forks source link

Null-returning getters on builders #121

Open alicederyn opened 8 years ago

alicederyn commented 8 years ago

I want to use the generated builders as "form backing objects" in Spring MVC views. The problem I'm having is that the builder throws IllegalStateException when getting a property that is not set, but in this case it would need to return null instead, while still doing unset checks when the "build" method is called. -- Germán Ferrari

alicederyn commented 8 years ago

I'm strongly against returning nulls from generated methods without being explicitly told to do so by the user, so this would need to be an annotation-driven extension to FreeBuilder. Thus far, we've not needed any extra annotations added to FreeBuilder, as everything necessary can be done with overrides and already-existing annotations (e.g. Nullable). I would prefer to keep this approach if we can—any suggestions on external annotations we could use?

Related: #41

gerferra commented 8 years ago

After thinking a bit more, what I would want is not "null returning getters", but to avoid the illegal state check on the getter of the generated builder. If I add @Nullable I lose the checking of existence on the "build()" method ...

gerferra commented 8 years ago

Maybe I could just override the getters in the cases I need it ...

alicederyn commented 8 years ago

As a workaround, you can definitely override the getters to catch the IllegalStateException and return a null instead.

gerferra commented 8 years ago

For your amusement: I'm removing the IllegalStateException on the getters using runtime bytecode manipulation (yuk!). I'm also adding getNullableX method to all Optional<T> fields, so I have symmetric setNullableX and getNullableX methods when using reflection ...

Both are ugly hacks, but help me realise what I really want. I need to interact with "old java" libraries and frameworks, which expects mutability, and javabean-like getters and setters accesible by reflection. It would be great if it could be possible to generate builders with this properties. These builders could act as adapters between the old and new java world ... The build method and everything that happens after building would stay the same as now.