函数与静态方法 [英] Functions vs. Static Methods
问题描述
我有一些处理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_get
与Cookie::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屋!