[Building Sakai] Java Help - Builder Pattern and Setters

Aaron Zeckoski azeckoski at unicon.net
Mon Aug 12 04:01:01 PDT 2013


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


On Sun, Aug 11, 2013 at 9:48 AM, Charles Severance <csev at umich.edu> wrote:
> Hi all,
>
> I have a Java question.
>
> I would like to use a builder pattern for my JSON stuff for LTI 2.0 in Sakai.  One of the things that I need to do is make all my setters return the instance.  So instead of:
>
> public void setThing(String thing) {
>   this.thing = thing;
> }
>
> I need to do something like this:
>
> public Stuff public void setThing(String thing) {
>   this.thing = thing;
>   return this;
> }
>
> My question is whether switching the return value from void to an instance, do I break all the other things in the world that look for Setters?
>
> Thanks.
>
> /Chuck
>
> P.S. I still hate setters and getters  - but the builder pattern is warming on me because of its type checking and being a little more self-documenting than massive constructors with seven String parameters.
> _______________________________________________
> sakai-dev mailing list
> sakai-dev at collab.sakaiproject.org
> http://collab.sakaiproject.org/mailman/listinfo/sakai-dev
>
> TO UNSUBSCRIBE: send email to sakai-dev-unsubscribe at collab.sakaiproject.org with a subject of "unsubscribe"



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


More information about the sakai-dev mailing list