2 Replies Latest reply on Sep 28, 2008 4:56 PM by 807589

    OOP Q about whether getters can really be avoided

    807589
      This is a general OOP question.

      There is a ClassA with a private instance variable consisting of an array of ClassB objects. ClassB has a private instance variable x. ClassA objects need to know something about the value of x for their array of ClassB objects; e.g x might be an int, and ClassA objects might need to know the sum over their ClassB objects of ClassB.x. How should this be done?

      An obvious approach is to define a getter in ClassB that returns the value of ClassB.x and have a method in ClassA that computes the sum. But this seems to violate encapsulation, because if the type of x is later changed, then the method in ClassA has to be changed as well, because it's expecting a certain return type from the getter. Having ClassB compute the sum doesn't solve the problem either, because the type of the sum depends on the type of x, so any method in ClassA that gets the sum from ClassB is vulnerable to a change in the type of x.

      This seems like a fairly common situation - how should it be handled?

      Thanks,

      Mark