Wednesday, October 12, 2005

Java vs. OO Design

For two years, I debated with one of our programmers about her object oriented (OO) design choices. In essence, she reduced a relational database driven Java application to a set of procedures losing almost all of the benefits of good object design. At the time, I was not studying industry trends and did not realize she was merely following current trends and best practices.

Now after studying industry trends and best practices, it seems that true OO design is slowly disappearing. However, I have stumbled upon one voice of opposition. Martin Fowler of ThoughtWorks has written an article on the AnemicDomainModel. In it, he suggests that developers are robbing their Domain Model by putting all of the logic in a service layer.

Mr. Fowler makes many of the same points I have made over the years. In fact, I'm reminded of the definition of an object as it has always been given to me:


An object consists of data and operations performed on that data.


In the Java world, JavaBean methods are not operations on the data. In fact, one has to wonder what benefit there is in creating getter and setter methods instead of just making the data public. In fact for objects (i.e. not base types), getter and setter methods are little more than public variables due to the returned value being a reference. In other words, the following C++ and Java are equivalent:

class A {
public:
Shape& getShape() { return shape; }
private:
Shape shape;
};

public class A {
private Shape shape;
public Shape getShape() { return shape; }
};

The difference is that the reference operator (&) in C++ makes the mistake much more obvious. Programmers I have employed did not even realize unintended consequences. It is even worse for setter methods:

public class A {
private Shape shape;
public void setShape( Shape shape ) { this.shape = shape; }
};

What happens if we have calling code like this:

Shape shape = (Shape) new Circle();
shape.setDiameter( 5 );
A a = new A();
a.setShape( shape );
.
.
.
shape.setDiameter( 10 );

What most Java developers do not understand is that the Shape object contained in class A refers to the Shape object created by the calling code. Consequently, the second Shape setDiameter invocation changes the size of the Circle stored in class A.

Most Java programmers reading this will probably disagree, but I challenge you to run an example and see what happens. As a side note, keep in mind that Strings are treated like base types.

So, after that lengthy tangent, the point is that a JavaBean is little more than a C struct, and a DAO is little more than a C module where every method takes a common struct as an argument.

OOPs...pun intended.

Labels:

0 Comments:

Post a Comment

<< Home