Java设计模式:管道和不可变性

huangapple go评论44阅读模式
英文:

Java design patterns: Pipeline and immutability

问题

我正在为我的后端服务工作,以支持类似管道的处理的轻量级框架。

  • 在管道中,每个阶段实际上是一个 Function<IN, OUT>,其中 IN 是前一阶段的 OUT
  • 每个阶段可以将其结果设置为数据模型(我们称之为 Record)。
  • 尽管输入是 IN(前一阶段的输出),但每个阶段都可以查看到目前为止的所有先前结果。

我的问题:

因此,实际上,每个阶段都可以将其结果设置为数据模型,并且可以获取到目前为止的所有其他结果。这使得模型在管道中的所有组件之间是共享和可变的。

这是否被视为反模式?如果是,您会对我的架构进行哪些更改?

谢谢

英文:

I'm working on a lightweight framework for my backend services to support a pipeline-like processing.

  • In the pipeline, each stage is essentially a Function<IN, OUT> where IN is the OUT of the previous stage.
  • Each stage can set its result to the data model (let's call it Record)
  • Although the input is IN (the previous stage's output), each stage can look at all previous results so far.

My question:

So essentially, each stage can set its result to the data model and can get all other results so far. That makes the model being shared and mutable among all components in the pipeline.

Would it be considered an anti pattern? If so, what changes will you make in my architecture?

Thanks

答案1

得分: 2

管道设计在线路中的组件彼此独立且保持独立时非常有效。例如,您可以在Web服务器过滤器链中看到它的使用(如Apache httpd过滤器或Java Servlet过滤器):链中的每个“链接”都可以检查请求和响应,可能进行修改。

当组件之间发展出隐藏依赖性时,管道设计很快就会变糟。隐藏依赖性是指链中的一个链接使用上游链接中完成的计算结果。这种依赖关系不受类型系统捕获,也不受测试覆盖,并且通常甚至没有文档记录。如果程序员现在修改或重构上游链接的代码,那么下游代码很可能会出现问题。在多个开发人员共同工作的大型系统中,隐藏的依赖关系会迅速出现,并导致代码变得脆弱且难以理解。

如果看到隐藏的依赖关系形成,最好将管道设计替换为使依赖关系图明确的设计。

英文:

The pipeline design is good when the components in the line are and remain independent of each other. You see it used for example in web server filter chains (like Apache httpd filters, or Java servlet filters): each "link" in the chain can inspect the request and response and potentially make modifications.

The pipeline design quickly goes bad, when the components develop hidden dependencies between each other. A hidden dependency is when one link in the chain uses the results from a computation that is done in an upstream link. This dependency is not captured by the type system, or covered by tests, and frequently it's not even documented. If a programmer now modifies or refactors the code for the upstream link, there's a good chance the downstream code breaks. In a large system that multiple developers work on, hidden dependencies will happen quickly, and result in code that is brittle and hard to understand.

If you see hidden dependencies form, it would be better to replace the pipeline design with a design that makes the dependency graph explicit.

huangapple
  • 本文由 发表于 2020年8月1日 21:17:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/63205632.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定