Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

OO programming concept question

Let's say I have an instance variable, someValue, and a method, doSomething, in a class, MyFirstClass.
Now say I have another class, MySecondClass.
Then, I instansiate MyFirstClass, firstClass = new MyFirstClass(), in another class, MyThirdClass, perhaps the class with my main() method in it, and I also instansiate MySecondClass, secondClass = new MySecondClass(), in MyThirdClass.
What if I want MySecondClass be able to check the value of someValue and run doSomething?
Do I have to give MySecondClass an instance variable as such: MyFirstClass refToFirstClass, and pass firstClass as an argument to the constructor of secondClass?
This seems to me like a bad idea for the reusability of MySecondClass. If I use MySecondClass in a program that doesn't use MyFirstClass then isn't there an extra, unused instance variable and constructor?
[877 byte] By [doubleoseven] at [2007-11-11 8:18:58]
# 1 Re: OO programming concept question
That is why OOP is a series of tradeoffs and design decisions.

If your design requires you to give MySecondClass direct access to the methods of MyFirstClass, you need to create a separate instance of MyFirstClass, or to receive a reference to the MyFirstClass object instantiated by MyThirdClass - which would seem most beneficial to your structure if this is what you want. So yes, you would write a constructor which took an instance of MyFirstClass as an argument. It would copy "by reference".

MySecondClass class2 = new MySecondClass( class1 );

This would allow you to know the state of someValue in the instance of MyFirstClass created by MyThirdClass.

[you can have several constructors, and it's no big deal to have a particular constructor used only in conjunction with MyThirdClass. However, this desire for re-use may argue in favor of the "alternate approach" discussed next.]

An alternative approach would be to have MyThirdClass pass the current state of someValue, or the value/object returned by doSomething(), as an argument to the method in class2, which would return the calculated value which would be needed by class3 ... class2.itsMethod( class1.doSomething()) is a perfectly valid method call ...
nspils at 2007-11-11 22:35:48 >