Re: instantiate instance variable of another class
smcardle@smcardle.com wrote:
On Sep 19, 9:58 pm, Steve <java...@gmail.com> wrote:
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.
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.
--
Lew