I ran into a code pattern today that I know isn't right and I know what to do about it. What I don't know is the best way to document for the original developer just why it needs to be changed. Obviously he thought it was a good design when he did it so I want to be prepared to respond with better than, "because I said" or "just because" when I discuss it.
I have two classes, for example, ClassA and ClassB. ClassA has a ClassB. ClassA passes a reference to itself into ClassB and calls the configure() method in its ClassB instance.
I see no reason to even have ClassB. In my view, ClassB knowing about its caller, ClassA, is definitely a bad smell in code. Since ClassB.configure only operates on ClassA objects, it really wants to be in ClassA.public class ClassA { ClassB instance = new ClassB(this); private String field1; private String field2; private String field3; public void main(String[] args) { instance.configure(classAData); } public void setField1(String value) { field1 = value; } public void setField2(String value) { field2 = value; } public void setField2(String value) { field2 = value; } } public class ClassB { public ClassB(ClassA classA) { this.classA = classA; } ClassA classA; public void configure(String[] classAData) { classA.setField1(classAData[0]); classA.setField2(classAData[1]); classA.setField3(classAData[2]); } }
One option is to move Field1, Field2, and Field3 into ClassB and let it be a data holder object for ClassA, if that fits the model. Another option is to eliminate ClassB all together. This is going to be my initial preference since the fields are used extensively in ClassA. As I refactor more I may find that I want a data object for ClassA but I don't see the point yet. In my real code, ClassA is a pretty extensive bit of code strewn with spaghetti and I'm trying to clean it up so I can make what is, as it is, a very difficult addition to the code. I am trying to refactor it to make it more object-oriented so that my change can be done in 30 minutes instead of a couple days - and then future changes will also be minutes instead of days.
What rules am I forgetting or do I need to research about children knowing about parent? It's clearly not loosely-coupled but I'd like to find documented theories or practices around this if I can. Any suggestions?
Thanks,
Dale