Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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()
share|improve this question
up vote 3 down vote accepted

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 :)

share|improve this answer
+1 Though actually, it is more of an adapter type approach: . 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. – Marjan Venema Jun 8 '11 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 Woodcock Jun 8 '11 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... – Marjan Venema Jun 8 '11 at 16:22
this approach is also compatible with the Law of Demeter – Steven A. Lowe Jun 8 '11 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.)

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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