Functions vs. Static Methods

前端 未结 4 1853
心在旅途
心在旅途 2020-12-16 15:01

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?

F

相关标签:
4条回答
  • 2020-12-16 15:35

    It would be a great idea, provided you are fully aware of the caveats involved. This is known as the Utility Pattern:

    Good candidates for utility classes are convenience methods that can be grouped together functionally.

    0 讨论(0)
  • 2020-12-16 15:43

    That would be a great way of organising your code, but why use static functions, just make a class for the required functionality.

    Or as said above use namespaces, but I'm not particularly familiar with the pros/cons of them.

    $cookie->get() is nicer to work with than cookie_get() in my opinion

    0 讨论(0)
  • 2020-12-16 15:46

    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.


    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.

    0 讨论(0)
  • 2020-12-16 15:56

    It's actually good practice to organize functions like that. A modern alternative would be to use a namespace.

    0 讨论(0)
提交回复
热议问题