开发者

Should an object "load" another object on its own, or have the other passed to it?

开发者 https://www.devze.com 2023-04-08 14:46 出处:网络
Is it a good practice to load another object from within an original object, like so: Class parent() {

Is it a good practice to load another object from within an original object, like so:

Class parent() {

    $child;

    function loadChild() {
        $child = new Child();
        $this->child = $child;
    }
}

or, should the child object always be passed in separately?

Class parent() {

    $child;

    function setChild(child $child) {
        $this->child = $child;
    }
}

$parent = new Parent();
$child = new Child();
$parent-开发者_StackOverflow中文版>setChild($child);

Which is the better option, more flexible etc?


It depends on the situation.

The name of the second object suggests that

  1. the Child instance will only be used by the Parent instance
  2. does not need to live longer than the Parent instance

If this is the case, than the first pattern (Object composition pattern) is the better one.

If the Child instance is needed/used at other places in you code, the second pattern (Dependency injection) is more appropriate. Dependency Injection is a more flexible pattern, if you are unsure about your use case, you should generally use the Dependency Injection.


The second option is more appropriate. It's called Dependency Injection. One of the main reasons to it is that you can pass any object that implements child interface (including mock object, which is important for TDD) without need to modify your class.


Depence on what you want. If you are sure you do not need to change child ever you can create it in the object. Less code => less errors. But if you might want to have different Childs later this would be bad.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号