« Return to Thread: Q: MOP, aspects, setter methods

Re: Q: MOP, aspects, setter methods

by Jochen Theodorou :: Rate this Message:

Reply to Author | View in Thread

grkuntzmd schrieb:

> I am a Groovy-Newbie and this is a theoretical question
>
> In a project I am working on, we have POJOs with setters of the
> following form:
>
> // Java Code
> public class Person {
>   private String name;
>
>   // Set the name value only if it changes, then mark the POJO dirty
>   public void setName(String name) {
>     if ((name == null) ? this.name != null : !name.equals(this.name)) {
>       this.name= name;
>       this.dirty = true;
>     }
>   }
> }
>
> Without arguing the philosophy of this approach, is it possible to use
> MOP in Groovy to automatically "inject" the equality checks and dirty
> flag setting (ala aspects)? As it stands, each of these setters needs
> unit testing because it contains "logic" code (as in Dierk König's
> interview on unit testing with Sven Haiges in the Grails podcast
> series). If the boilerplate setter code could be injected, these methods
> would not each need separate units tests.

If you add/change/replace a setter using MOP, then Java still won't see
that change. That means if Person#setName is called from Java, then it
will always be the old method... which implies that there has to be an
old method too,

Now if you write that class in Groovy, then there is the option to hook
into the compilation process. For example you could use our new AST
tranformations to annotate the properties to generate that code for you.
Of course such a setter is callable from Java too then.

But your motivation should not be to safe unit tests, it should be to
safe code duplication. Also the code above could be put in a helper:

> public class Person {
>   private String name;
>
>   // Set the name value only if it changes, then mark the POJO dirty
>   public void setName(String name) {
>     PropertyHelper.dirtySet("name",this,name)
>   }
> }
>
> class PropertyHelper {
>   static void dirtySet(String name, instance, value) {
>     if (value == instance.@"$name") return
>     instance.@"$name" = value
>     instance.@dirty = true
>   }
> }

Person can be Java or Groovy, PropertyHelper would be in Groovy and can
be tested on its own. (note: == is in Groovy different from Java)

bye blackdrag


--
Jochen "blackdrag" Theodorou
The Groovy Project Tech Lead (http://groovy.codehaus.org)
http://blackdragsview.blogspot.com/
http://www.g2one.com/

---------------------------------------------------------------------
To unsubscribe from this list, please visit:

    http://xircles.codehaus.org/manage_email


 « Return to Thread: Q: MOP, aspects, setter methods