title: Accessing object methods with composition?
body: <p>This is probably a very simple thing, but I just can't seem to work this out on my own. When using composition, what's the best way to access the methods of the "inner object?" Every way I can work out seems to violate some OO principle or other.</p>
  
  <p>This is kind of a very broad topic, but I'll include an example just to make things clear as can be. The code's written in java, but I believe this question applies to pretty much any language that uses OOP.</p>
  
  <pre><code>Class Shelf {
      private Book book;
  }
  
  Class Book {
      public void turnPage() {
          //do stuff
      }
  }
  </code></pre>
  
  <p>What would be the best way to access Book's methods when you only have access to the Shelf object? A few places I've read suggest wrapper methods within Shelf, since it follows the Law of Demeter. However, this doesn't seem to be the best option for every case. </p>
  
  <p>First of all, many of the inner object's methods may have nothing to do with main class, so it wouldn't make any sense to have the main class implement wrappers for every method, and it would most likely break the Single Responsibility Principle. Furthermore, if the inner object was used for composition in a large number of other classes, all needing to do the same thing, it would lead to a lot of needless code duplication, making your code much less DRY.</p>
  
  <p>My first instinct was to have a simple getBook() method, to give access to the book to operate the methods directly. It makes more sense to get a book off the shelf and turn the page, rather than tell the shelf to turn the page of its book for you. However this seems to break both encapsulation and the Law of Demeter. The same applies if I were to make the book variable public final.</p>
  
  <p>Am I missing something? Or overcomplicating things? I can't seem to wrap my head around this, so I'd greatly appreciate some help.</p>