i've been facing a common situation at work that has happened quite often when handling objects.

The situation goes like this:

You have to realted classes A and B, class A has an instances of class B. Now, imagine that we want to call methodB of class B, but we only have access to an intance of class A. What's the best approach to this situation and why:




where methodB is implemented as follows:

function methodB()
  return self.getClassBInstance()->methodB()

2 Answers 2


Go with Ainstances->methodB();

Give A a copy of the method that simply drops down onto its B instance.

That way, if you ever decide to refactor, for example if you decide to move methodB from A's B instance to a new class, C, you'll have less refactoring to do.

This is known as the façade pattern, and has saved me a lot of hours of painful work on many occasions :)

  • +1 Though actually, it is more of an adapter type approach: en.wikipedia.org/wiki/Adapter_pattern . Facade is usually more geared towards hiding an entire application/package behind a single class. Adapater is specifically geared towards hiding child classes/objects from the outside. Commented Jun 8, 2011 at 15:51
  • Hmm, I always thought the adapter pattern was more geared towards parsing data imports and other transformation tasks. I considered this the facade pattern because it's basically abstracting a procedure behind an external wrapper.
    – Ed James
    Commented Jun 8, 2011 at 16:14
  • understandable. A facade is an adapter or is an adapter a facade?. I'd say they mostly differ in scope where the adapter usually is hiding only its own inner instances and a facade can be hiding an entire API like the MS Office Object model interface... Commented Jun 8, 2011 at 16:22
  • this approach is also compatible with the Law of Demeter Commented Jun 8, 2011 at 19:39

The latter - that is, methodB() wrapping self->getClassBInstance()->methodB() - hides from A's users the fact that A uses B. That reduces coupling.

(This is an example of applying the Law of Demeter.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.