Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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:

Ainstances->getClassBInstance()->methodB();

or

Ainstances->methodB()

where methodB is implemented as follows:

function methodB()
{
  return self.getClassBInstance()->methodB()
}
share|improve this question
add comment

2 Answers 2

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: 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. –  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
add comment

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
add comment

Your Answer

 
discard

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.