if this question was already answered, please tell me; I was only able to find the usual "what's a public/private/protected" question!

So here is my question: When do I use private methods and when do I create a new class with public methods instead?

Example:

class MyActualWorker {
    public function work() {
        $this->helperMethod1();
        $this->helperMethod2();
    }

    private function helperMethod1() {
        ...
    }

    private function helperMethod2() {
        ...
    }
}

Alternative:

class MyActualWorker {

    public function __construct() {
        $this->helperObject = new HelperObject();
    }

    public function work() {
        $this->helperObject->helperMethod1();
        $this->helperObject->helperMethod2();
    }
}

When do I use the first example, when the second? For me the primary advantage of the second example is UnitTesting is really easy.

I am grateful for any answer!

有帮助吗?

解决方案

Usually, you use the first.

The "Delegation Pattern" (which is using sub-objects) is a great way to have different implementations of methods you can swap out at runtime - but if you don't need that, it's just unnecessary overhead.

Another common case are what I call "library methods", that is, methods that are not tied to any objects but stateless an just perform some calculations. Those can be delcared public staticand moved to an abstract class. YOu don't create objects for that kind of relationship though (just classes with static methods), so it's entirely different to your example.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top