简体   繁体   English

OOP:私有方法与新类

[英]OOP: Private methods vs new class

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. 对我来说,第二个示例的主要优点是UnitTesting非常容易。

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 static and moved to an abstract class. 可以将它们放在public static然后移到抽象类中。 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 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM