On April 17, 2020, I start a huge project to migrate the
Future[T] from legacy playframework project to
ZIO. Three months later, after tens of thousands of lines
of code modification, the migration was a complete success. In
September, I used this experience as the background to share in the
Chinese Scala Meetup community with the title "Introduction
to ZIO". In this share, I explained a fanatic imageation,
在这次分享中,我展望了一个美好的愿景,借由 ZIO 的类型参数
R
提供的抽象能力来实现代码的可移植性,和提高可测试性。但想在遗留项目中实现这个愿景并不容易,主要挑战来自遗留项目的代码耦合,和开发者的思维惯性。如今,这个愿景已经达成。我会在这篇
Post 中与你分享我的进化之路。
What is R
A ZIO[R, E, A] value is an immutable value that lazily
describes a workflow or job. The workflow requires some environment
R, and may fail with an error of type E, or
succeed with a value of type A.
objectdjx314extendsAppwithDemo{ val mixer = newMixer() val oven = newOven() val pipingTip = newPipingTip() val turntable = newTurntable() val baker = newBaker(oven, mixer) val decorator = newDecorator(mixer, pipingTip, turntable) val candyMaker = newCandyMaker val scChef = newSichuanChef val hnChef = newHunanChef val cashier = newCashier val waiter = newWaiter val washer = newWasher val logistic = newLogistic val security = newSecurity val accountant = newAccountant val manager = newManager val cs = newCakeShop( baker, decorator, candyMaker, scChef, hnChef, cashier, waiter, washer, logistic, security, accountant, manager )
cs.simpleCake() .onComplete(println)
}
I just want to test a small part of the functions, why do I need to
construct all dependent instances. Why do I have to do so much
preparation to test this simple function. Because it belongs to the
method of the class, and this class has too many construction
parameters, these construction parameters are unnecessary for the
function we want to test
若想让工程代码最大程度上可移植、可测试,一个简单易行的方法是:不要在类中编写与对象无关(no
use this)的函数,将他们移动到 object 中(in
java: mark method
static)。同时,编写引用透明的代码对达成这一目标有正面作用。
但是,在遗留项目中实现这一点有些困难,
因为大多数开发者都把依赖注入框架错用了,就像上面的反面教材一样。Even
Spring contributors made the same mistake. See: Spring's
sample project
Too many irrelevant dependencies have brought huge obstacles to the
portability of codes, turning them into ad hoc codes that are difficult
to test.
The whole system is like a balls made up of strings and knots.
Current Situation
社区中的方案... zio layer 每次 unsafeRun
都会重新生成,这很纯函数式,但这不适合 web 服务。例如连接池