OO Design: What goes into the constructor?

M

Martin Gregorie

Lew said:
Your reasoning is quite sound. I'd phrase the principles involved a
little differently, but I'd bet I'd come up with the same conclusions.
I've come to Java from C with almost no formal background or training in
OOD techniques. In C I've developed a personal pseudo-OO style that just
growed because it minimizes bad interactions. In it I store variables as
control-block structs (very similar to the way that the FILE struct is
used) or as globals with their scope limited to the source file if
there's never more than one "instance" possible per program. All access
to these variables are solely via functions. I also write functions
equivalent to constructor and destructor. The major difference is that,
because the constructor function can return a status code, I'll often do
the equivalent of parsing the option definition string within it. I
think its arguable whether that counts as part of initialization: my
conclusion has been that in C the constructor is a good place to put it
but in Java its often better to split it out.

This seemed like a good place in the thread to check whether this is
sensible, so thanks for your feedback.
While I said that constructors can legitimately throw exceptions, I
didn't say they should, necessarily.
>
I assumed that was what you meant.
Then I'd likely reject that idea and treat null args the same as empty
args, oi.e., no options.
Which is exactly what it does :)

I also use setters to handle seldom used options rather than multiple
constructors. An example would be to turn option case sensitivity on
(default is off).
 
M

Martin Gregorie

Joe said:
One particular instance I can think of is to throw an
IllegalArgumentException if arguments are passed that just don't make
any sense.
Agreed, though validation generally requires more processing than
I'd now do in the constructor. I'm with Lew here. Also, suitable
choice of parameters (using booleans in place of ints or strings
and/or passing appropriate classes) can hand off quite a bit of simple
validation to the compiler.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,262
Messages
2,571,054
Members
48,769
Latest member
Clifft

Latest Threads

Top