开放原则和Java“最终”修改 [英] Open-closed principle and Java "final" modifier

查看:106
本文介绍了开放原则和Java“最终”修改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

开放原则规定软件实体(类,模块,功能等)应该开放扩展,但关闭修改。



然而,Joshua Bloch在着名的着作有效Java中提出了以下建议:继承的设计和文档,否则禁止它,并鼓励程序员使用final修饰符来禁止子类化。



我认为这两个原则明显相互矛盾(我错了吗?)编写代码时你遵循哪个原则,为什么?你是否打开你的课程,不允许继承他们(哪些?),或者尽可能使用最后的修饰符?

解决方案

坦白说,我认为开放/封闭的原则更是一个不合时代的时代。从80年代和90年代开始,当OO框架建立在一切原则上,即所有东西都必须继承自其他东西,并且所有东西都应该是子类化的。



这在UI中是最典型的像MFC和Java Swing这样的时代的框架。在Swing中,你有可笑的继承,其中(iirc)按钮扩展复选框(或其他方式)给出其中一个未被使用的行为(我认为这是它的setDisabled()调用复选框)。为什么他们分享祖先?没有理由,而且他们有一些共同的方法。



这些日子的构成比继承更受青睐。默认情况下,Java允许继承,.Net采用了(更现代)的方式,默认情况下禁止它,我认为这是更正确的(更符合Josh Bloch的原则)。



Josh Bloch还指出,继承破坏了封装,并给出了一些很好的例子。还有人证明,如果通过委派而不是扩展类来改变Java集合的行为更加一致。



我个人主要将继承视为一个实现详细这些天。


The open-closed principle states that "Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification".

However, Joshua Bloch in his famous book "Effective Java" gives the following advice: "Design and document for inheritance, or else prohibit it", and encourages programmers to use the "final" modifier to prohibit subclassing.

I think these two principles clearly contradict each other (am I wrong?). Which principle do you follow when writing your code, and why? Do you leave your classes open, disallow inheritance on some of them (which ones?), or use the final modifier whenever possible?

解决方案

Frankly I think the open/closed principle is more an anachronism than not. It sems from the 80s and 90s when OO frameworks were built on the principle that everything must inherit from something else and that everything should be subclassable.

This was most typified in UI frameworks of the era like MFC and Java Swing. In Swing, you have ridiculous inheritance where (iirc) button extends checkbox (or the other way around) giving one of them behaviour that isn't used (I think it's its the setDisabled() call on checkbox). Why do they share an ancestry? No reason other than, well, they had some methods in common.

These days composition is favoured over inheritance. Whereas Java allowed inheritance by default, .Net took the (more modern) approach of disallowing it by default, which I think is more correct (and more consistent with Josh Bloch's principles).

DI/IoC have also further made the case for composition.

Josh Bloch also points out that inheritance breaks encapsulation and gives some good examples of why. It's also been demonstrated that changing the behaviour of Java collections is more consistent if done by delegation rather than extending the classes.

Personally I largely view inheritance as little more than an implemntation detail these days.

这篇关于开放原则和Java“最终”修改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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