Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an object based on the state of another object in Java

Tags:

java

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.

like image 541
Stanley kelly Avatar asked Jan 23 '10 15:01

Stanley kelly


3 Answers

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);
like image 67
Tom Jefferys Avatar answered Oct 07 '22 01:10

Tom Jefferys


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?

like image 44
Yoni Avatar answered Oct 07 '22 01:10

Yoni


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.

like image 33
Tom Hawtin - tackline Avatar answered Oct 07 '22 03:10

Tom Hawtin - tackline