I am working on Java for some time. I saw there are too many talks about decoupling the objects. I see they say "new" keyword is considered as symbol of high coupling. I did not get any answer till now why it is. can anyone explain me?
Well new
creates an instance of a specific class. So whenever you use new
you are creating coupling between the class being created and the code that creates it. Example:
List<String> strings = new ArrayList<>();
creates an instance of ArrayList
, which is a problem if you don't need to hard-wire the code to use that specific implementation of the List
API.
Note that Java new
doesn't allow you to make the class name a parameter. Not even with generic type parameters.
The alternative is to use a factory function or object, or use dependency injection to decouple the code that needs the instance of a class from the procedure that creates it. (Or pass around Class
objects as parameters and use reflection to create instances.)
Of course, this doesn't answer the implied question about whether the coupling incurred by new
is harmful. That depends on the context.