加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么OOP中静态类的最佳实践有所不同?

发布时间:2020-12-15 04:22:10 所属栏目:Java 来源:网络整理
导读:我目前正在阅读有关 Java最佳实践的内容,我发现根据 this book,我们必须支持非静态的静态类.我记得在C#最佳实践中,我们必须根据Dennis Doomen的C#3.0,4.0和5.0编码指南来避免这种情况: AV1008 – Avoid static classes With the exception of extension met
我目前正在阅读有关 Java最佳实践的内容,我发现根据 this book,我们必须支持非静态的静态类.我记得在C#最佳实践中,我们必须根据Dennis Doomen的C#3.0,4.0和5.0编码指南来避免这种情况:

AV1008Avoid static classes

With the exception of extension method containers static classes very often lead to badly designed code. They are also very difficult,if not impossible,to test in isolation unless you’re willing to use some very hacky tools. Note If you really need that static class,mark it as static so that the compiler can prevent instance members and instantiating your class. This relieves you of creating an explicit private constructor.

我在C# answer和Java answer中找到了这两个用于避免静态类的时间,但仅仅是出于好奇 – C#和Java都是OOP语言,为什么它与最佳实践完全不同呢?

更新:
我不能从Java书中复制这么多页面,但底线是:

If you declare a member class that does not require access to an
enclosing
instance,always put the static modifier in its declaration,making it a static
rather than a nonstatic member class. If you omit this modifier,each instance will
have an extraneous reference to its enclosing instance. Storing this reference costs
time and space,and can result in the enclosing instance being retained when it
would otherwise be eligible for garbage collection (Item 6). And should you ever
need to allocate an instance without an enclosing instance,you’ll be unable to do
so,as nonstatic member class instances are required to have an enclosing instance.
A common use of private static member classes is to represent components of
the object represented by their enclosing class.

它只是关于性能吗?

请注意,这个问题更多的是关于静态类和OOP,而不是Java和C#之间的差异.

解决方法

JoshuaBloch给出的建议也适用于c#,给出的建议也适用于c#(在谈论静态类时).

Why use static members?

>他们不需要实例来调用它们
>在c#中,他们使用call opcode,它不需要检查null(这是微优化)而不是实例方法(使用callvirt opcode).我相信类似的东西也会出现在java中.
>如果不使用实例,它们不会阻止GC中的某些内容.
>也没有将此引用传递给隐藏的所有方法的开销.

如果您已经习惯了视觉工作室的Resharper生产力工具,它将提供与JoshuaBloch给出的相同的建议,在c#中说Method can be made static在给定链接中是合理的.

Why not use static members?

>它们不易测试(容易).
>他们无法实现接口成员.
>它们不能通过依赖注入注入.
>他们不参与多态(在面向对象语言中非常需要).
>在c#中,静态类不能作为引用传递.

因此,如果您了解它们并且它们同时适用于这两种语言,那么这两个建议都很好.在适当时使用它们,当它们不适合时避免使用它们.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读