Oops, That should be public Foo getFoo() and public Foo getAlwaysFoo() ofcourse
On Wed, Nov 26, 2014 at 6:28 PM, Niels Basjes <ni...@basjes.nl> wrote: > Hi, > > I have a Java project where I'm using Avro as the serialization technology. > I have a deep nested structure and many fields are optional. > > Because of the 'random' nature of my application I want to be able to > simply 'set' a value in that tree easily. > > So I want to have a setter in my class that looks like this (Assume > myStruct is an instance of the 'root' class generated by Avro): > > public void setSomething(String value) { > myStruct > .getFoo() > .getBar() > .getOne() > .getOther() > .setSomething(value); > } > > The 'problem' I ran into is that any of the 4 get methods can return a > null value so the code I have to write is really huge. > For every step in this method I have to build null checks and create the > underlying instance if it is null. > I already started writing helper methods to do this for parts of my tree. > > To solve this in a way that makes this code readable I came up with the > following which I want to propose to you guys (before I start working on a > patch). > > My idea is to generate a new 'get' method in addition to the existing > normal get method for the regular instance of the class. > > So in addition to the > > public void getFoo() { > return foo; > } > > I propose to generate something like this as well > > public void getAlwaysFoo() { > if (foo == null) { > setFoo(Foo.newBuilder().build()); > } > return foo; > } > > This way the automatically created instance immediately has all the > defaults I have defined. > > Assuming this naming my code will be readable because it will look like > this: > public void setSomething(String value) { > myStruct > .getAlwaysFoo() > .getAlwaysBar() > .getAlwaysOne() > .getAlwaysOther() > .setSomething(value); > } > > I can create this same effect in my own project code. > But having this automatically generated by the Avro engine would make life > a lot easier. > > Is this an idea you guys would consider to have in the main (Java) > generated code base? > If so, is the 'getAlways' prefix sensible? > > -- > Best regards > > Niels Basjes > -- Best regards / Met vriendelijke groeten, Niels Basjes