我有一个包含14个静态方法和4个静态属性的类-不好吗? [英] I have a class with 14 static methods and 4 static properties - is that bad?

查看:118
本文介绍了我有一个包含14个静态方法和4个静态属性的类-不好吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在写一个正好450行长的PHP类,它包含14个静态方法和4个静态属性以及6个常量(以及私有的__construct()__clone()).

I have been writing a PHP class that is exactly 450 lines long and it contains 14 static methods and 4 static properties as well as 6 constants (and private __construct() and __clone()).

我想知道这里是我做错什么了吗,我的班级是邪恶的吗?

I am wondering here is that am I doing something wrong, is my class evil?

使用该类时,总是调用一个方法,例如:

When you use the class, you always call a single method like:

MyClass::coolMethod();

,然后您将其完全搁置,因此感觉使其可构建会很愚蠢吗?

and then you leave it alone altogether so it feels that it would be stupid to make it constructable?

用它构造对象确实没有多大意义,因为它更像是一个包含一些可以直接调用的方法的工具.

There's really not much point in constructing objects out of it, because it is more like a tool that contains a few methods that you can just call directly.

实际上,在这14种方法中,有7种是公共的-其余的是私有的,可供该类使用.

Actually, out of those 14 methods, 7 of them are public -- the rest are private for the class to use.

推荐答案

您应尽量避免staticglobal.

统计信息给您带来了全局变量给您带来的相同缺点.无论何时使用任何类方法,都将对该类的依赖项硬编码为使用代码.结果是难以维护的紧密耦合代码.可以通过完全避免使用静力学来避免这种情况并严格使用依赖项注入.

Statics give you the same disadvantages globals give you. Whenever you are using any class methods, you are hardcoding a dependency on that class into the consuming code. The result is less maintainable tightly coupled code. This can easily be avoided by avoiding statics altogether and a disciplined use of Dependency Injection.

您不能注入并传递静态类,因此例如当您必须对它们进行单元测试(静态方法是可测试性的终结.

You cannot inject and pass around static classes, so for instance when you have to unit-test them, you cannot mock them (or at least only with some effort). It's just plain painful. Static methods are death to testability.

此外,请记住,类只能做一件事. 他们应该承担单一责任.遍历全班,看看那里是否有其他地方最好放一些东西,以避免编写神级.

Also, keep in mind that classes should do only one thing. They should have a single responsibility. Go through your class to see if there is stuff in there that's better placed somewhere else to avoid writing a God Class.

这篇关于我有一个包含14个静态方法和4个静态属性的类-不好吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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