一个类只有静态字段和方法是不好的做法吗? [英] Is it bad practice for a class to have only static fields and methods?

查看:22
本文介绍了一个类只有静态字段和方法是不好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个由静态成员变量和静态方法组成的类.本质上,它用作通用实用程序类.

I have a class that consists only of static member variables and static methods. Essentially, it is serving as a general-purpose utility class.

一个类只包含静态成员变量和静态方法是不好的做法吗?

推荐答案

不,我根本不这么认为.更糟糕的做法是让一个类充满实例方法,而这些方法实际上并不依赖于特定实例.使它们静态告诉用户它们的用途.此外,您可以通过这种方式避免不必要的实例化.

No, I don't think so at all. It is worse practice to have a class full of instance methods which don't actually depend on a particular instance. Making them static tells the user exactly how they are intended to be used. Additionally, you avoid unnecessary instantiations this way.

作为事后的想法,总的来说,我认为避免仅仅因为"使用语言特性是好的,或者因为你认为那是Java 实现方式".我记得我的第一份工作,我有一个充满静态实用程序方法的类,一位高级程序员告诉我,通过使我的所有方法全局化",我并没有完全利用 Java 的面向对象的力量.6 个月后,她不在团队中.

As an afterthought, in general I think its nice to avoid using language features "just because", or because you think that that is the "Java way to do it". I recall my first job where I had a class full of static utility methods and one of the senior programmers told me that I wasn't fully harnessing the OO power of Java by making all of my methods "global". She was not on the team 6 months later.

这篇关于一个类只有静态字段和方法是不好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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