为什么StringBuilder是最终的 - 与所有最终方法相比? [英] Why is StringBuilder final - versus having all final methods?

查看:112
本文介绍了为什么StringBuilder是最终的 - 与所有最终方法相比?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的回答(一厢情愿)对早期关于StringBuilder最佳实践的问题。如果StringBuilder是可扩展的,那么特定于域的子类可以扩展其流畅的接口,这将收紧StringBuilder传递给许多构建更大字符串部分的方法的代码。

The motivation for this was my answer ("Wishful thinking") to an earlier question on StringBuilder best-practices. If StringBuilder was extensible, then domain-specific subclasses could extend its fluent interface, which would tighten up code where a StringBuilder gets passed around to a lot of methods that build parts of a larger string.

我正在考虑向番石榴人提出建议 - 也许是StringBuilder委托。

I'm considering suggesting something - maybe a StringBuilder delegate - to the Guava folks.

还有什么其他目的它是否适用于StringBuilder是最终的,而不是只有最终方法?

What additional purpose does it serve for StringBuilder to be final, as opposed to just having final methods?

推荐答案

如果所有方法都是最终方法那么当前无法修改StringBuilder的行为。它的子类必须添加未连接的行为(本质上是糟糕的设计)或使用旧的新功能,例如便利方法。如果你想做后者,最好有一个提供相关功能但包含StringBuilder而不是扩展它的类。正如约书亚布洛赫所说,宁愿遏制继承。简而言之,如果所有方法都是最终的,那么没有充分的理由来扩展课程,你也可以将它作为最终方法。

If all methods are final then the current behaviour of StringBuilder cannot be modified. Subclasses of it must add either unconnected behaviour (which is inherently bad design) or new functionality which uses the old, such as convenience methods. If you want to do the latter it is probably better to have a class that provides the relevant functionality but contains a StringBuilder rather than extends it. As Joshua Bloch says, "prefer containment over inheritence". In short, if all methods are final there is no good reason to extend the class, and you may as well make it final too.

这篇关于为什么StringBuilder是最终的 - 与所有最终方法相比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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