Link to home
Start Free TrialLog in
Avatar of Rohit Bajaj
Rohit BajajFlag for India

asked on

Should one define a variable with new() in a class or should one inject it

Hi,
I have a class :
public class AuthenticationManager {

    private static final Logger _logger = LoggerFactory.getTrimmer(AuthenticationManager.class.getSimpleName());
    private final List<Listener> _listeners = new ArrayList<Listener>();
    private boolean _verificationInProgress = false;
    private final CallStateReceiver callStateReceiver = new CallStateReceiver();


I was wondering is it a good practice to have the line :
    private final CallStateReceiver callStateReceiver = new CallStateReceiver();

or should one chnage it to private final CallStateReceiver callStateReceiver ; and get it set from outside ?

What way can we define this ?

Thanks
ASKER CERTIFIED SOLUTION
Avatar of kaufmed
kaufmed
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Agree with kaufmed.

If you instantiate the object inside the class, your code is tightly coupled and dependent on the objects created using new(). Best approach is, as suggested by kaufmed, to provide the objects from outside.

Consider a case in future if you have another flavor of CallStateReceiver (say MyCallStateReceiver) and you want to use it in place of CallStateReceiver. How will you do it ? It is not possible if you instantiate the object inside the class, you will need to have mechanism (ie. setter or constructor) where objects can be provided outside the class.

Hope the explains.
Avatar of Rohit Bajaj

ASKER

HI,
I did not understand the point -
Consider a case in future if you have another flavor of CallStateReceiver (say MyCallStateReceiver) and you want to use it in place of CallStateReceiver. How will you do it ? It is not possible

MyCallStateReceiver will also have the object inside it.. how is it not possible. please clarify exactly what you mean.

thanks
Hi,
Can you please give an example of :
 Even better, you might define an interface that lays out the minimum criteria that your class expects from an object.