Java: Static Class?

2019-01-04 21:30发布

I have a class full of utility functions. Instantiating an instance of it makes no semantic sense, but I still want to call its methods. What is the best way to deal with this? Static class? Abstract?

7条回答
狗以群分
2楼-- · 2019-01-04 22:08

Private constructor and static methods on a class marked as final.

查看更多
【Aperson】
3楼-- · 2019-01-04 22:10

Just to swim upstream, static members and classes do not participate in OO and are therefore evil. No, not evil, but seriously, I would recommend a regular class with a singleton pattern for access. This way if you need to override behavior in any cases down the road, it isn't a major retooling. OO is your friend :-)

My $.02

查看更多
家丑人穷心不美
4楼-- · 2019-01-04 22:11

Sounds like you have a utility class similar to java.lang.Math.
The approach there is final class with private constructor and static methods.

But beware of what this does for testability, I recommend reading this article
Static Methods are Death to Testability

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2019-01-04 22:11

There's no point in declaring the class as static. Just declare its methods static and call them from the class name as normal, like Java's Math class.

Also, even though it isn't strictly necessary to make the constructor private, it is a good idea to do so. Marking the constructor private prevents other people from creating instances of your class, then calling static methods from those instances. (These calls work exactly the same in Java, they're just misleading and hurt the readability of your code.)

查看更多
该账号已被封号
6楼-- · 2019-01-04 22:15
  • Final class and private constructor (good but not essential)
  • Public static methods
查看更多
beautiful°
7楼-- · 2019-01-04 22:19

comment on the "private constructor" arguments: come on, developers are not that stupid; but they ARE lazy. creating an object then call static methods? not gonna happen.

don't spend too much time to make sure your class cannot be misused. have some faith for your colleagues. and there is always a way to misuse your class no matter how you protect it. the only thing that cannot be misused is a thing that is completely useless.

查看更多
登录 后发表回答