The Artima Developer Community
Sponsored Link

Legacy Design Forum
When to Bean



This page contains an archived post to the Design Forum (formerly called the Flexible Java Forum) made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.


Class objects as data containers

Posted by Paul J. Lewis on September 20, 2000 at 7:05 PM

To me, the use of a Class with all fields public, really seems to miss the
point of having a class in the first place. May be have some very good
reason for doing it like this, but to me you class looks very much
like a C struct (i.e. it is just an aggregation of fields).

For a very simple class, say a co-ordinate, it may make sense, since any
combination of two integer (say) is a valid coordinate, then the x and y fields
may as well be public.

But for the class you describe surely there are some rules about the
data that could be enforced by making the class a 'real' Java class, and providing
set/get methods.

Are all of the String fields you describe allowed to be null? If not
why not enforce that rule (perhaps by having the constructor throw
an exception)? Are the price and volume fields allowed to be negative?

If enforcing these rule is too cumbersome in the class itself I'd consider
have no public constuctor, but instead a factory method that enforces the
rules (to create a Trade) and other objects that provide services/actions on
Trade that do enforce those rules.

By the way, you class does have state (to be precise 4 Java string objects,
and 3 Java integers). What your class don't have is any invalid states; any
4 Strings (including null) and any 4 integers stored in your class, are a valid
Trade object.

I suppose you can look at it two ways: either allow all possible states for
an object and have the code that manipulates the objects enforce and state validity
rules (and the more you use the class to more of this code there is).
Or you can have the class (or package or similar) enforce these rules, thereby limiting
the scope of places that invalid state can be introduced into a Trade object.

Anyway, that's just my tuppence on this subject. =8-)


Sponsored Links

Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us