Value Objects with Getters/Setter Interface
Recently, I’ve built the client side of a J2EE Transfer Object pattern implementation and it composes a number of value objects. I was going to shape the VO’s like in Darron Schall’s Book VO used in his “Convert Generic Objects into Class Instances” article (good read I might add). The VO consists of an object with public attributes and nothing else.
public class Book
{
public var title:String;
public var pageCount:int;
public var publishedDate:Date;
public var inLibrary:Boolean;
// Just for kicks...
public var random:*;
} // end class
I was contemplating whether to use getter/setter methods using the get & set keywords. It would allow me to parse information that was coming in as Strings but return it in the type it was needed.
A little bit of net research led me to this nice article that using get methods and set methods can add more flexibility in the future.
1) Get methods can return a default value if it’s undefined/null
2) Get methods can be used to trigger lazy instantiation: Why create instantiate the object of a linked attribute at the time of the VO’s initialization when you can do it at the time you need?
3) Set methods can perform validation: This was the main reason why I considered getter/setters with VO’s.
4) You can have multiple getters for the same private attribute: Very cool, didn’t realize how handy this could be.





January 6th, 2007 at 10:03 am
If your getters and setters are just generic on the client side, then don’t use them. You can always refactor later.. In Java, if you change to getters/setters from public vars, the interface to your class changes, which is a problem. In ActionScript, the interface is the same no matter what approach you take.
I talked about this here, a couple years ago, and I much prefer public vars over get/set: http://www.darronschall.com/weblog/archives/000149.cfm
March 21st, 2007 at 2:30 pm
A way that I stumbled on whilst trying to simplify some code was to extend the ObjectProxy class, attach it to the VO, and override the setProperty() on the (VO)Proxy to handle whatever transformations you might want to make. if (itemName == “prop1″){ value = stringToDate(value) }. Not canonical, but it turned out nice.