Suppose I have a class
public class MyMainClass {
SomeGlobalStateObject someGlobalStateObjectInstance;
public MyMainClass(SomrDep1 someDep1, SomeDep2 someDep2){
this(someDep1); // call the other constructor so that I can initialize, the base layer is the same
someGlobalStateObjectInstance.setGlobalVariable("someVar", someDep2); // I have overriden setGlobalVariable for "someVar", seems like a smell.
}
public MyMainClass(SomeDep1 someDep1){
someGlobalStateObjectInstance = new someGlobalStateObjectInstance();
someGlobalStateObjectInstance.setGlobalVariable("someVar", null); // The null in the second param is a key part of my problem. Assume this must be done, I cant remove this line for this constructor.
// do lots of other things with someGlobalStateObjectInstance.
}
}
The above is the current design for this class. You can assume that I must create someGlobalStateObjectInstance
in the constructor and it cant be passed as a dependency itself.
Here is my main problem now. As you see, I first called someGlobalStateObjectInstance.setGlobalVariable("someVar", null);
in the second constructor, and then in the first one I override again with someGlobalStateObjectInstance.setGlobalVariable("someVar", someDep2);
.
Is this a code smell? It is unnecessarily setting a variable and then overriding in the first constructor. I am wondering how to best tackle this to avoid all code smells.