instantiate instance variable of another class

S

Steve

If I want to instantiate instance variable of another class, which
approach do you suggest? What's the difference between the following
two methods? Please advice. thx.

Method 1:
=======
public class DataUtil
{ private CustInfo cust;
public DataUtil()
{ cust = new CustInfo();
}
}

Method 2:
=======
public class DataUtil
{ private CustInfo cust = new CustInfo();
}
 
R

Roedy Green

Method 1:
=======
public class DataUtil
{ private CustInfo cust;
public DataUtil()
{ cust = new CustInfo();
}
}

Method 2:
=======
public class DataUtil
{ private CustInfo cust = new CustInfo();
}

if every constructor does this, you might as well use method 1 to make
sure it always gets done.

Method 2. has nicer behaviour if there is an exception. It is easier
to track down exceptions if they don't happen in static or instance
init code.

Method 2 would be forced on you if wanted to pass parms to the
CustInfo constructor.

Note, normally you would define that beast as final. That makes sure
you don't inadvertently initialise it twice.
 
M

Mark Space

Method 2. has nicer behaviour if there is an exception. It is easier
to track down exceptions if they don't happen in static or instance
init code.

Method 2 would be forced on you if wanted to pass parms to the
CustInfo constructor.

What about lazy initialization? Method 2 is nicer if CustInfo is large,
has a complicated constructor, or may become large in the future. If
DataUtil is never used, method 2 never allocates a Custinfo() if no
DataUtil's are created.

Just my quick observation...
 
I

Ingo R. Homann

Hi,

Mark said:
What about lazy initialization? Method 2 is nicer if CustInfo is large,
has a complicated constructor, or may become large in the future. If
DataUtil is never used, method 2 never allocates a Custinfo() if no
DataUtil's are created.

Just my quick observation...

IMHO, none of the two methods has anything to do with lazy
initialization. Both methods have the same behaviour in this context!

Ciao,
Ingo
 
L

Lew

Statement belongs on separate line from brace.

Statement belongs on separate line from brace.

Statement belongs on separate line from brace.
Mark said:
What about lazy initialization? Method 2 is nicer if CustInfo is
large, has a complicated constructor, or may become large in the
future. If DataUtil is never used, method 2 never allocates a
Custinfo() if no DataUtil's [sic] are created.
none of the two methods has anything to do with lazy
initialization. Both methods have the same behaviour in this context!

Method 2 will initialize cust in any constructor the class has, including the
default constructor as is shown. Any constructor added to the class will
initialize cust. (Not lazily.)

Method 1 will only initialize cust in the default constructor, as shown.
Another constructor would have to independently initialize cust.

As Ingo points out, the initialization in neither case is lazy.
 
S

smcardle

If I want to instantiate instance variable of another class, which
approach do you suggest? What's the difference between the following
two methods? Please advice. thx.

Method 1:
=======
public class DataUtil
{ private CustInfo cust;
public DataUtil()
{ cust = new CustInfo();
}

}

Method 2:
=======
public class DataUtil
{ private CustInfo cust = new CustInfo();



}- Hide quoted text -

- Show quoted text -


In my oppinion both methods are incorrect. This is closely coupling
two classes i.e. the DataUtils class requires close coupling to the
CustInfo class i.e. you cannot create a DataUtil instance without
first creating a CustInfo instance. Testing your DataUtil using say
JUnit and mock objects would become difficult because you cannot
instanciate a DataUtil class without first instanciating a CustData
class.

The better way to do this (and I mean ALWAYS) is to have CustInfo
extend an interface, then have the interface as a private variable
instead of the actual class as you have in your example and either
pass in a pre instanciated CustInfo to either a constructor of the
DataUtil or via a method i.e. say something like "public void
setCustUtil(CustUtilI custUtil) { this.custUtil = custUtil; }"

This allows for loose coupling in that if your CustUtil gets big Or
requires constructor parameters of its own OR requires other objects
to be instanciated during the construction phase then creating a mock
of CustUtil from its interface is easy and your testing of DataUtil
becomes isolated.

Try to keep all code like this to an absolute minimum, always try to
program to interfaces and remember LOOSE coupling HIGH cohesion = GOOD
OO...

Steve
 
L

Lew

In my oppinion both methods are incorrect. This is closely coupling
two classes i.e. the DataUtils class requires close coupling to the
CustInfo class i.e. you cannot create a DataUtil instance without
first creating a CustInfo instance. Testing your DataUtil using say
JUnit and mock objects would become difficult because you cannot
instanciate a DataUtil class without first instanciating a CustData
class.

Sooner or later a class will have concrete instance variables.
The better way to do this (and I mean ALWAYS) is to have CustInfo
extend an interface, then have the interface as a private variable

Nah, not always. Sometimes a cigar is just a cigar.
instead of the actual class as you have in your example and either
pass in a pre instanciated CustInfo to either a constructor of the
DataUtil or via a method i.e. say something like "public void
setCustUtil(CustUtilI custUtil) { this.custUtil = custUtil; }"

While Dependency Injection (DI), like other patterns, is incredibly useful
when it's useful, it isn't a panacea.
This allows for loose coupling in that if your CustUtil gets big Or
requires constructor parameters of its own OR requires other objects
to be instanciated during the construction phase then creating a mock
of CustUtil from its interface is easy and your testing of DataUtil
becomes isolated.

Try to keep all code like this to an absolute minimum, always try to
program to interfaces and remember LOOSE coupling HIGH cohesion = GOOD
OO...

The principle is good, but not absolute.

Never, ever generalize.
 
N

nebulous99

Statement belongs on separate line from brace.

Stylistic criticism belongs after the answer to the OP's question and
should be polite rather than terse.
Statement belongs on separate line from brace.

Stylistic criticism belongs after the answer to the OP's question and
should be polite rather than terse.
Statement belongs on separate line from brace.

Stylistic criticism belongs after the answer to the OP's question and
should be polite rather than terse.
Mark said:
What about lazy initialization? Method 2 is nicer if CustInfo is
large, has a complicated constructor, or may become large in the
future. If DataUtil is never used, method 2 never allocates a
Custinfo() if no DataUtil's [sic] are created.
Ingo said:
none of the two methods has anything to do with lazy
initialization. Both methods have the same behaviour in this context!

Method 2 will initialize cust in any constructor the class has, including the
default constructor as is shown. Any constructor added to the class will
initialize cust. (Not lazily.)

Method 1 will only initialize cust in the default constructor, as shown.
Another constructor would have to independently initialize cust.

As Ingo points out, the initialization in neither case is lazy.

The lazy initialization angle was presumably in that method 1 lends
itself to delaying initialization in a future revision more than
method 2 does. Method 1 also lends itself to initializing the ivar
differently in different constructors, and is needed anyway if the
initial state the ivar should have (so its constructor parameters) are
only determined at run-time.
 
L

Lew

Stylistic criticism belongs after the answer to the OP's question and
should be polite rather than terse.

This isn't "stylistic criticism" but an objective technical comment based on
the standard Java coding conventions, as promulgated by Sun since 1999 and
presumably as much part of any Java programmer's education as how to use the
ternary operator or Javadoc comments. Comments in the newsgroup-preferred
"trimmed inline" style belong immediately subsequent to the relevant material,
as you ably demonstrated with your comments.

"Criticism" implies fault-finding, which I was not doing. This newsgroup is
for the discussion of Java-related issues. The use of Java source-code
conventions is well within that purview, and saying what the convention is
implies no more criticism than any other technical comment.

Use of source-code conventions is based on the notion of "literate
programming", a human-factors concept that aims to increase code quality and
reduce maintenance costs, and to improve communication between practitioners.
These are sound, pragmatic motivations for espousing, and teaching, the
standards not only for APIs, but for code documentation.

Ignore at your, and the community's, peril.
 
B

bbound

This isn't "stylistic criticism"

Sure it is. The code is syntactically and semantically valid but
there's something you don't like about it. That something appears to
be its formatting. Formatting is an aspect of style. Hence, stylistic
criticism.
Use of source-code conventions is based on the notion of "literate
programming", a human-factors concept that aims to increase code quality and
reduce maintenance costs, and to improve communication between practitioners.
These are sound, pragmatic motivations for espousing, and teaching, the
standards not only for APIs, but for code documentation.

I don't disagree. However, the OP asked one question and you responded
with, at first, irrelevancies. Making comments or criticisms, however
valid, that are orthogonal to the asked question, before getting
around to answering that question (or, worse, in lieu of answering it)
is not especially nice and repeating such comments especially gives a
flavor of nitpicking to your posting. Combine that with the brusque
manner in which it was done and you cross the line into having
actually been (mildly) rude. This is what set Ed off, too, remember?
(Not that his over-the-top response to your behavior was any better,
mind; indeed, it was clearly much worse.)

I'm unsure why only I (and, I think, Roedy) seem to even notice the
frequent (albeit mild) rudeness of yours (and Andrew's) responses to
newbies; in particular it's been pointed out to (both of) you
repeatedly and you seem incapable of recognizing it. I suppose this
latest attempt to alert you to it is therefore futile, but doing
nothing would be even more so. But your attitude (and Andrew's) will
put new people off ever returning to this newsgroup and should change.
What a newbie sees when they find one of your responses is some picky
grammarian being more concerned with elements of style in their code
(or their English prose, even) than with the actual problem they asked
for help with (assuming, as is usually the case, that that problem was
something else). You don't see it that way. But they do.

Please save the nitpicking of their code (other than whatever is the
actual source of their complaint) for after the addressing of their
question, and make it more polite in tone (and ixnay on the pointless
repetition!) ...

If you went to a doctor with a bum knee, would you prefer he quickly
prescribe the painkillers or whatever it is you need, or spend the
first 3/4 of the time lecturing you for fifteen minutes about how you
really shouldn't smoke, repeating it three times word for word, first?
Even if after writing the prescription he reminded you to watch other
aspects of your health that he saw were cause for concern, I think
you'd prefer that to his basically changing the subject to your
smoking (or whatever) right off the bat and changing it back only much
later. Your priority is the knee. You want it fixed, or at least
something for the pain. The generic, unrelated health advice can wait.

Same with peoples' Java issues when they post here.
 
R

Roedy Green

Stylistic criticism belongs after the answer to the OP's question and
should be polite rather than terse.

The polite way to do this is to reformat the code, posted it and say
"I tidied your code to make it clearer what you
were doing."
 
L

Lew

Roedy said:
The polite way to do this is to reformat the code, posted it and say
"I tidied your code to make it clearer what you
were doing."

My interest is not to reformat the code but to assist the OP.

This is a discussion forum for Java matters. Presumably we're all engineers
here and interested in facts. I neither intended nor implied criticism,
simply to convey relevant engineering factors to the OP for their benefit.

I state facts as facts. "It's raining outside." "Statements should not
appear in source on the same line as the opening brace."

This rests on the understanding that the context for source-code convention
discussions is the widely-accepted set of source-code conventions, and that
the professionals in this groups are interested in adhering to professional
standards for everyone's benefit. Perhaps I rely too much on people having
that attitude.

Furthermore, this is a free-ranging discussion group. Sometimes discussion of
one matter, creating an instance, brings up other matters, the use of literate
programming conventions, for example. Should we feel so shut down and
mistrustful of each other that we cannot broach such topics, for fear of
unleashing a vitriol of accusations of, yes, stylistic impropriety?

Ironic that the criticism leveled is far more exemplary of the problem about
which it purports to complain than the original remark was.
 
B

bbound

I state facts as facts. "It's raining outside." "Statements should not
appear in source on the same line as the opening brace."

I trust you realize that if someone asked about where to initialize a
variable and you responded first with "It's raining outside" that this
is obviously irrelevant and even rudely changing the subject?

Well it's not much better if it's Java-related, but still not the
answer to their question.
Furthermore, this is a free-ranging discussion group. Sometimes discussion of
one matter, creating an instance, brings up other matters, the use of literate
programming conventions, for example.

Especially when you or Andrew reply, as both of you just *love* to
bring up that particular other matter, for whatever reason. And I
don't claim that you should never do so. But save it for a P.S. and
phrase it more politely. It's not so much that you do so, but the way
you do so that comes off as rude and, especially when you a) put it
earlier than the answer in your post and b) devote more lines of your
post to it than you do to the answer, seems dismissive of the poster's
original question. Of course on the (thankfully infrequent) occasions
where that's ALL that's in the post (or something else equally
orthogonal, such as a tangent regarding English grammar or cross-
posting or some other favorite topic of yours), it's especially so --
you might as well be saying "go away and come back when you speak
perfect English without an accent and your code is tidied up to my
standards, and then I might deign to help with the actual problem you
were having".

It's simple respect to give your attention (and therefore, the
beginning of your reply) first to the question they specifically
asked, and only then to asides about anything else in their code (even
other outright bugs if you spot any).
 
L

Lew

It's simple respect to give your attention (and therefore, the
beginning of your reply) first to the question they specifically
asked, and only then to asides about anything else in their code (even
other outright bugs if you spot any).

You raise interesting points. Thank you.
 

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

No members online now.

Forum statistics

Threads
473,772
Messages
2,569,591
Members
45,103
Latest member
VinaykumarnNevatia
Top