Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / September 2007

Tip: Looking for answers? Try searching our database.

instantiate instance variable of another class

Thread view: 
Steve - 19 Sep 2007 20:58 GMT
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();
}
Roedy Green - 19 Sep 2007 22:37 GMT
>Method 1:
>=======
[quoted text clipped - 10 lines]
>{ 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.

Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Mark Space - 20 Sep 2007 01:54 GMT
>> Method 1:
>> =======
[quoted text clipped - 10 lines]
>> { private CustInfo cust = new CustInfo();
>> }

> 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...
Ingo R. Homann - 20 Sep 2007 11:02 GMT
Hi,

>>> Method 1:
>>> =======
[quoted text clipped - 17 lines]
>
> 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
Lew - 20 Sep 2007 14:39 GMT
Steve wrote:
>>>> Method 1:
>>>> =======
>>>> public class DataUtil
>>>> { private CustInfo cust;

Statement belongs on separate line from brace.

>>>>  public DataUtil()
>>>>  { cust = new CustInfo();

Statement belongs on separate line from brace.

>>>>  }
>>>> }
[quoted text clipped - 3 lines]
>>>> public class DataUtil
>>>> { private CustInfo cust = new CustInfo();

Statement belongs on separate line from brace.

>>>> }

Mark Space wrote:
>> 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.

Signature

Lew

nebulous99@gmail.com - 21 Sep 2007 15:10 GMT
> Steve wrote:
> >>>> Method 1:
[quoted text clipped - 3 lines]
>
> 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.

> >>>>  public DataUtil()
> >>>>  { cust = new CustInfo();
>
> 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.

> >>>>  }
> >>>> }
[quoted text clipped - 5 lines]
>
> 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 Space wrote:
[quoted text clipped - 13 lines]
>
> 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.
Lew - 21 Sep 2007 16:32 GMT
>> Steve wrote:
>>>>>> Method 1:
[quoted text clipped - 5 lines]
> 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.

Signature

Lew

bbound@gmail.com - 21 Sep 2007 17:10 GMT
> >>>>>> public class DataUtil
> >>>>>> { private CustInfo cust;
[quoted text clipped - 4 lines]
>
> 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.
Roedy Green - 21 Sep 2007 17:17 GMT
>> >>>>  public DataUtil()
>> >>>>  { cust = new CustInfo();
[quoted text clipped - 3 lines]
>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."
Signature

Roedy Green Canadian Mind Products
The Java Glossary
http://mindprod.com

Lew - 21 Sep 2007 17:25 GMT
>>>>>>>  public DataUtil()
>>>>>>>  { cust = new CustInfo();
[quoted text clipped - 5 lines]
> "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.

Signature

Lew

bbound@gmail.com - 21 Sep 2007 17:34 GMT
> 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).
Lew - 21 Sep 2007 17:42 GMT
> 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.

Signature

Lew

smcardle@smcardle.com - 21 Sep 2007 12:59 GMT
> If I want to instantiate instance variable of another class, which
> approach do you suggest? What's the difference between the following
[quoted text clipped - 18 lines]
>
> - 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
Lew - 21 Sep 2007 14:19 GMT
>> If I want to instantiate instance variable of another class, which
>> approach do you suggest? What's the difference between the following
[quoted text clipped - 26 lines]
> 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
[quoted text clipped - 5 lines]
> program to interfaces and remember LOOSE coupling HIGH cohesion = GOOD
> OO...

The principle is good, but not absolute.

Never, ever generalize.

Signature

Lew



Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.