July 31, 2017

OOP question #1 (encapsulation, coupling)

Scenario: I have an object A that has some mutator methods, and I have another object B that uses A, and that requires exclusive access to it.

Only B can use said mutator methods. If I change A externally I will break B's internal state.


$a = new A;
$b = new B($a);
$a->change(); // $b is fucked up.

What I and many others would do to solve this is:


public function B::__construct(){ $this->a = new A(); }

A is hardcoded in B's constructor and inaccessible from the outside.

Now, B could work with any object that implements A's interface, but I'm denying myself this possibility, as A is tightly coupled to B.

Question is: why we do that?

I can enforce the coupling externally if I wanted, in a factory for example:


function getSafeB(){
    return new B(new A); // A will be inaccessible externally.
}

What are your thoughts about this? Let me know in the comments.

3 comments:

  1. `$b` is fucked up only when his interface isn't giving what B expected in other (most) cases it might work.

    ReplyDelete
  2. You could create an abstract class and hardcode the dependencies in the subclass.

    - Ryan F.

    ReplyDelete
    Replies
    1. yes, basically the same thing. but i like the abstract class as it's not directly instantiable. thank you for you comment

      Delete

OOP question #1 (encapsulation, coupling)

Scenario: I have an object A that has some mutator methods, and I have another object B that uses A, and that requires exclusive access to i...