函数与静态方法 [英] Functions vs. Static Methods

查看:75
本文介绍了函数与静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些处理cookie的功能.通过将它们移动到自己的类并使用它们作为静态方法来将它们分组会是一个可怕的想法吗?

I've got a few functions that deal with cookies. Would it be a horrible idea to group them by moving them to a class of their own and use them as static methods?

功能:

function cookie_get(){}
function cookie_set(){}
function cookie_delete(){}

静态方法:

class cookie
{
    static function get(){}
    static function set(){}
    static function delete(){}
}

推荐答案

是的,这很可怕,因为

Yes, that would be a horrible idea because static methods are hard to test and mock. Why not just create a real Cookie class that you can configure at runtime with those methods as regular methods.

如果您只想将这些功能分组到一个包中,也可以

If you just want to group those functions into a package, you can just as well use Namespaces.

编辑:自从您在注释中提到它:是的,出于任何测试目的,常规函数与静态函数一样不可测试.因此,您的初始情况就像将其更改为使用静态类一样可怕".甚至伪名称空间也没有给您带来任何好处,因为您已经将其应用于常规函数. cookie_getCookie::get一样好.

Edit: Since you brought it up in the comments: yes, for any testing purposes regular functions are as untestable as statics. So your initial situation is as "horrible" as changing it to use a static class. Even the pseudo namespace is not giving you any advantage, because you already applied that to your regular functions as well. cookie_get is as good or bad as Cookie::get.

这篇关于函数与静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆