Sunday, May 01, 2005

Model Objects Properties

Well - as a kind of a follow up on my post regarding using XML as model objects, I just thought - why not make all property access methods (get/set) package scoped??AND only allow acces to a certain object thru an access-object. I know many will think, well this breaks the "encapsulation" principle of the OO idea, but I beg to differ as there are many cases where this is exactly what you want, to instead end up putting logic into the get/set methods, which IMO is a bad idea.
Well - lets spill it, here are my thoughts in pseudo-code:

interface MyModelObject {
String getSomeString();
void setSomeString(String str);

Plain interface.. nothing new here

class MyModelObjectImpl {
private String someString;
public String getSomeString() { return someString; }
/* package */ void setSomeString(String str) { this.someString = str; }

Actual model object (container), please note it DOES NOT implement the MyModelObject interface as Im changing scope on the setSomeString method to be more restrictive.

class MyModelObjectNullAccess implements MyModelObject {
.. just delegates straigt-thru to the actual MyModelObjectImpl wrapped ..

A simple NULL type access object which only delegates straight thru to the wrapped MyModelObjectImpl. This DOES implemente the MyModelObject is it should..

class MyModelObjectValidationAccess implements MyModelObject {
.. May use some sort of validation only allowing string staring with "Homer" to be
set as someString ..

Again - a simple access class which DOES implement the MyModelObject interface, but rather this implementation may validate the string given to the setSomeString method and may even be connected to the struts validation framework - adding a ValidationError to the form's list of error, thus you have a server-side validation framework directly on-top of your model-objects, so even though another "user" (class) might try to set an invalid value, you'd still get an exception or whatever..
So, from the point of the users, the access class IS the model-object, but you're able to switch behaviour based upon need.. Meta-Object Protocol (MOP) like.

Well, till next time..


Post a Comment

<< Home