2 Replies Latest reply: Sep 28, 2008 11:56 AM by 807589 RSS

    OOP Q about whether getters can really be avoided

      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?


        • 1. Re: OOP Q about whether getters can really be avoided
          I would say, you don't gain anything by having getters in this case.
          It is quite common for one piece of code to have dependencies on other pieces of code.
          It up to you to decide that when you change the type of x, the return type of the sum changes.
          • 2. Re: OOP Q about whether getters can really be avoided
            In the absence of other constraints, do whatever takes the least work at the time.

            In the abstract case you give, there's no driver one way or the other.

            It's quite natural that an OrderItem might have a cost, and something want to look at the cost and total it with an exterior sum.

            It's quite natural that a RocketBooster might contribute thrust to a ThrustTotal and so use an interior sum.