Your question shows some misconceptions, I guess: if the alternative to
passing an object as parameter
is to create a new instance directly in the constructor
PassTheObjectHere, then you are obviously not using any values/state of the previously created
PassTheObjectHere. If that is the case, it is pretty useless to pass
obj as a parameter to
PassTheObjectHere. In fact, in such a case I would typically check if
TheObject has any member variables, which might make it a candidate for a static class (but don't get me wrong, I am not telling you the usage of a static class would improve the design here in any way).
On the other hand, if the constructor of
PassTheObjectHere needs the values / state of the previously created
obj to work properly, it would be plain wrong to have a constructor like this.
var obj = new TheObject();
// ... do something which expects having obj
// ... some values provided by the caller
(I hope this is obvious).
can passing the object too many times cause some bad effects on the program?
This is not a question of "too many times". You can pass objects around 1000 times correctly, which is fine, and one time wrong, which is bad. For example, if you pass obj to the constructor, and the constructor changes the state of
obj in a way the caller does not expect (called a "side effect")
// ... use methods/properties/values of obj
// ... for this constructor
// and finally
and you caller does something like
public class ClassWithTheObject
TheObject obj = new TheObject();
PassTheObjectHere anotherObj = new PassTheObjectHere(obj);
then your program now has a bug. There are mainly the following alternatives to protect you from that:
- Avoid the side effect by not changing "obj" within the constructor
- If you need to change "obj", make a copy beforehand within the constructor.
- do not add any methods to
TheObject which allow the change of any internal state of obj (which is called "immutability")
Number 3 leads to the same code as 1, but with the additional protection against introducing unintentional side effects at a later point in time, when
PassTheObjectHere might be changed.