Search code examples
javafactory-pattern

In what terms does new operator is considered harmful?


Factory pattern is supposed to be used when using new operator for creating object is considered harmful. In what terms does new operator is considered harmful


Solution

  • Using of new operator directly is hardcoding.

    It also means that class is not following single responsibility principle.

    Factories along with interfaces allow long term flexibility:

    • It allows decoupling and therefore more testable design.
    • It allows you to introduce an Inversion of Control (IoC) container easily.
    • It makes your code more testable as you can mock interfaces.
    • It gives you a lot more flexibility when it comes time to change the application (i.e. you can create new implementations without changing the dependent code).

    Hope this helps.