[Building Sakai] Java Help - Builder Pattern and Setters

Aaron Zeckoski azeckoski at unicon.net
Mon Aug 12 09:31:36 PDT 2013


If java have return based method overloading you could have done this as well...

public void setThing(String thing) { .... }
public Thing setThing(String thing) { .... }

But since it does not.... that will simply fail to compile.
I think making other methods is probably the safest option.

Maybe
public Thing buildThing(String thing) { .... }

Then you know exactly when you are using builders.
-AZ


On Mon, Aug 12, 2013 at 12:22 PM, Charles Severance <csev at umich.edu> wrote:
> Thanks - this is exactly what I needed.   Sounds like the smart approach is
> to add separate builder-style methods to parallel the setter methods to
> avoid reflection glitches.
>
> public void setThing(String thing) {
>  this.thing = thing;
> }
>
> public Thing thing(String thing) {
>
>  this.thing = thing;
>  return this;
> }
>
> /Chuck
>
>
> On Aug 12, 2013, at 7:01 AM, Aaron Zeckoski <azeckoski at unicon.net> wrote:
>
> Jackson and most everything else in the java world which works with
> reflection is pretty strict about how it looks for setters and getters
> on objects (mostly because they almost all use the same reflection
> engine underneath). Generally speaking, getters just have no params
> and must not return void and must start with get or is (if returning
> boolean). Setters must start with set and have a void return and a
> single param. The method must be public or at least default class
> visible.
>
> There are exceptions (aside from the reflectutils I wrote) like the
> grails reflection engine which has special rules for ignoring certain
> runtime fields added by the GORM stuff (which is actually hibernate
> underneath) and working with groovy objects (which tend to have all
> dynamic getters and setters).
>
> All that said, putting lots of extra setters on your class is totally
> fine because if they don't have a matching getter then most
> serialization engines will simply ignore them during processing.
> Deserialization might be a little more tricky but if the library bases
> it on the built in java reflection then it will not pick up on any
> setter unless it has a matching getter and meets the rules above so
> you are probably fine there as well.
>
> -AZ
>
>



-- 
Aaron Zeckoski - Software Architect - http://tinyurl.com/azprofile


More information about the sakai-dev mailing list