在Java中的不可变对象? [英] Downsides to immutable objects in Java?

查看:103
本文介绍了在Java中的不可变对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Java中不可变对象的优点似乎很清楚:




  • 一致状态

  • 自动线程安全

  • 简单



您可以通过使用私有final字段和构造函数注入来支持不变性。 / p>

但是,在Java中支持不可变对象的缺点是什么?



ie




  • 与ORM或网络演示工具不兼容

  • 不灵活的设计?

  • 实现复杂性?



是否可以设计主要使用不可变对象的大型系统(深对象图)?

解决方案


但是,
有什么缺点有利于Java中的不可变对象?
与ORM或web
演示工具不兼容


基于反射的框架由于不可变对象而复杂,因为它们需要构造函数注入:




  • Java中没有默认参数,这迫使我们始终提供所有必要的依赖关系

  • 构造函数覆盖可以是凌乱的

  • 构造函数参数名通常不通过反射来实现,这迫使我们依赖于依赖关系解析的参数顺序




执行复杂性?


创建不可变对象仍然是一项无聊的任务;编译器应该处理实施细节,如 groovy


是否可以设计主要使用不可变对象的大型系统(深对象图)?


绝对是的;不可变对象为其他对象创建了很好的构建块(他们喜欢组合),因为当您可以依赖其不可变组件时,更容易维护复杂对象的不变量。我唯一真正的缺点是创建许多临时对象(例如 String concat是过去的一个问题)。


The advantages of immutable objects in Java seem clear:

  • consistent state
  • automatic thread safety
  • simplicity

You can favour immutability by using private final fields and constructor injection.

But, what are the downsides to favouring immutable objects in Java?

i.e.

  • incompatibility with ORM or web presentation tools?
  • Inflexible design?
  • Implementation complexities?

Is it possible to design a large-scale system (deep object graph) that predominately uses immutable objects?

解决方案

But, what are the downsides to favouring immutable objects in Java? incompatibility with ORM or web presentation tools?

Reflection based frameworks are complicated by immutable objects since they requires constructor injection:

  • there are no default arguments in Java, which forces us to ALWAYS provide all of the necessary dependencies
  • constructor overriding can be messy
  • constructor argument names are not usually available through reflection, which forces us to depend on argument order for dependency resolution

Implementation complexities?

Creating immutable objects is still a boring task; the compiler should take care of the implementation details, as in groovy

Is it possible to design a large-scale system (deep object graph) that predominately uses immutable objects?

definitely yes; immutable objects makes great building blocks for other objects (they favor composition) since it's much easier to maintain the invariant of a complex object when you can rely on its immutable components. The only true downside to me is about creating many temporary objects (e.g. String concat was a problem in the past).

这篇关于在Java中的不可变对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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