design patterns – Different composition techniques from the perspective of the client

(second try, i already asked a similar question to this here: Adding behaviour and more behaviour…. using more classes for it, but in the commend section it became clear that my question was misunderstood, so i asked it again more focused; i will remove this comment here and the old post a few days later)

There exists different composition arts/techniques, i will present in the following some of them.

The question then is do you know more techniques additional to my presented ones?

And then the important question is, what kind of different makes it from the client perspective, how should i access from a client a compositionend objectgraph or in an other way asked, which composition-technique is client-friendly in the context of a good object orientented design, which depends on the Law of Demeter?

Which other dependencies could be out there, let me go more into that direction (using the compostion A) and what to go into an other direction (using composition B)

i have choosen my examples with the approach extending a root object, which is initially used by the client in its behaviour:

This question is related to that one: No trivial god-class refactoring

i have an object and a few methods in it

class MyObject{
  
  ...

  doSomething1(){}
  doSomething2(){}

}

and now i want to extend this object with more methods, for example a doSomething3
which acts on the state of that object and maybe on some kind of “own” state.

so there are now different ideas how i can achieve this:

  • add this method + its more membervariables, which are needed, to the existing class
  • create a new class MyObject2 and write it down into this class

if i decide for the secound solution, then the question is how to combine MyObject and MyObject2

  • I can integrate MyObject2 into MyObject

    class MyObject {
    
      MyObject2 myObject2 = new MyObject2(this)
      ...
    
      doSomething1(){}
      doSomething2(){}
    
    }
    
  • i can let MyObject2 standalone, but when is the question, how the client get access to MyObject2, if he has access to MyObject

  • Third class, that combine the other two

     class ThirdClass {
    
       MyObject myObject = new MyObject()
       MyObject2 myObject2 = new MyObject2(myObject)
    
     }
    

The client have then in option 1) and option 3) the following possibilities:

....myObject.getMyObject2().doSomething3();
....thirdClass.getMyObject2().doSomething3();