Lets say you have a class called Explosion where it does not make sense to create an instance of it, without some information from another class instance. The constructor is not made public.
Is it better to do it this way:
// both classes are in the same package
Explosion e;
Collision c = new Collision()
// do some stuff with collision
e = c.createExplosion()
Or is it better for Explosion to have a static method for creating an instance and you pass in a Collision object as an argument:
Explosion e
Collision c = new Collision()
// do some stuff with collision
e = Explosion.createExplosion(c)
When you are the author of both classes.
Why is the constructor not public? It would seem sensible to me for Explosion to have a constructor that takes a Collision reference as a parameter.
That way you could have:
Explosion e;
Collision c = new Collision();
// do some stuff with collision
e = new Explosion(c);
I prefer the second approach as it better divides the responsibility between the classes. To answer your question ask yourself who has the responsibility to create an Explosion, and act accordingly. Your second approach basically uses a factory method to hide the constructor, but the responsibility is still within the Explosion class, which is good IMO.
Why is the constructor not public? can you make it package visible and then just pass the Collision as a constructor parameter?
It depends... largely on dependency.
If you consider Explosion
always a lower-level or a peer of Collision
, then go for the flexibility and ease-of-use of a (virtual) instance method. This keeps behaviour in objects, and reduces the need for getters (which tend to be a sign of poor design). You still of course have a call to the Explosion
constructor, only now it is within Collision
.
If, on the other hand, Collision
should not depend upon Explosion
then go for a constructor directly. This is not the end of virtual methods. If things get more complicated you might change the calling code to call a virtual method on some other object that creates a specific configuration of Explosion
from a passed in Collision
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With