编程语言
首页 > 编程语言> > java-公共静态方法-一个不好的迹象吗?

java-公共静态方法-一个不好的迹象吗?

作者:互联网

我刚刚在这里阅读了这篇文章:http://hamletdarcy.blogspot.com/2008/04/10-best-idea-inspections-youre-not.html,尤其是最后一点让我考虑了我的代码,特别是建议:

What in the world is a public method doing on your object that has no dependency on any fields within the object? This is certainly a code smell. The problem is that the “auto-fix” for the inspection is to apply the static keyword. Nooooo. That’s not what you want to do. A public method without any dependency on object state can’t possibly be part of an object that has one clearly stated charter. It’s just not cohesive and should be placed somewhere else. So: if the method is private, accept the auto-fix, but if the method is public then don’t.

所讨论的代码本质上是一个对象转换器.它接受类型为A的对象,并将其转换为其他类型.

我的层次结构是这样的:

接口ObjectTransformer-> GenericObjectTransformer

然后在此之下,通过ObjectTransformerA和ObjectTransformerB扩展GenericObjectTransformer

现在,ObjectTransformerA和ObjectTransformerB都需要一些功能,但实际上并不依赖GenericObjectTransformer的任何实例变量,因此它是GenericObjectTransformer中受保护的静态方法.

这是否违反上述规则?显然,这是受保护的而不是公共的,但是它仍然是可从类外部访问的方法,而该方法与类本身无关?

有什么想法吗?

解决方法:

我不同意你摘录的摘录.

A public method without any dependency on object state can’t possibly be part of an object that has one clearly stated charter. It’s just not cohesive and should be placed somewhere else. So: if the method is private, accept the auto-fix, but if the method is public then don’t.

仅仅因为方法是静态的并且与状态没有关系,并不意味着它属于“低内聚”类别.凝聚力/功能不是基于状态.

当您尝试确定凝聚力时,请考虑整个类的作用,而不仅仅是实例变量.如果您要查看的逻辑与通用概念(GenericObjectTransformer)有关,则将其保留在那里.

如果按惯例来计算月球的轨道或海洋的深度,则将其移至实用程序类(我们领域的另一个有臭味的区域).

标签:public-method,inheritance,static,java
来源: https://codeday.me/bug/20191023/1916617.html