Home > Mobile >  What if i instantiate all the classes in one function and call that function every where?
What if i instantiate all the classes in one function and call that function every where?

Time:07-18

if i have n classes and instantiate all the classes in one function, what are the major drawbacks for this . ex bellow :-

class A{}
class B{}
class C{}
.
.
class Z{}



main(){
new classA()
new classB()
.
.
.
new classZ()

}

and where ever I need any class. I just call the main method. I know that this is bad , but and IOC should be used , but what are the major disadvantages of using this ?

CodePudding user response:

It is more fragile for a class to rely on something external that might not be there rather than something it can accept as parameter, check once and use internally.

Also in your example all classes will rely on a shared instances of the others so everything is intermingled and one piece of code can change the state of an other object and affect another - what's the point of dividing the code into classes if it is all tangled up?

That doesn't mean you have to use IOC framework. you can still instantiate classes and pass them as parameters manually if that make sense in your scenario

CodePudding user response:

Looking at your current code, there are few things which needs attention:

  1. Your application may consume more memory than needed since you are instantiating all the objects regardless of whether they are needed or not. Disposing objects is also something to consider here.

  2. Depending on how you code, you would end up having undesirable shared or multiple instances of one or more classes.

  3. There is nothing stopping calling methods to create there own instance unless this a library that does not expose constructors to outside world.

  4. Scope for variables will be same whether it is desired or not.

  5. Determining return type of the method could itself limit your design options for rest of the application.

  • Related