nicoespeon.abracadabra
VSCode Pluging for JS/TS Refactoring- VSCode Native TypeScript Refactoring Method
- 針對主要的 method 往下拆成 private method
- 將相似的 method 分類拆成獨立 class
- 將獨立 class 分別移動至獨立檔案
- [DI] 將新獨立出來的 class 建立 Interface
- [DI] 將新獨立出來的 class 統一由 Constructor 注入
- [Decorator] 從分拆的主要 function 前後開始觀察是否有可以拆成以裝飾器實作的動作
- 那些不需要與主要任務有需要直接耦合的任務
auth.isVaild()
裡的 notifyauth.isVaild()
驗證動作裡的帳號是否鎖定的前置檢查
- 那些不需要與主要任務有需要直接耦合的任務
- https://refactoring.guru/design-patterns/decorator/typescript/example
- 在要做事的 function 前 (參數) / 後 (回傳值) 動手腳
- 但 Interface 還是相同
- 在今天課程例子裡,auth flow 裡送 slack 通知並不是主要 feature
- 因此可以使用裝飾器模式,在
isVaild()
return false 時,送 Slack 通知即可
- 因此可以使用裝飾器模式,在
- TypeScript 5.0 預計實作 ECMAScript Decorators 提案
- ECMAScript Decorators 終於進入 Stage 3.0 了
- [過時舊資訊] 是否应该在production里使用typescript的decorator?
- Decorator Order is Matter; 順序很重要
- 可能 Unit-Test 都過,但整合起來就是有問題
- 靠 Code Review 避免
- 或只拆成一個 Decorator 就沒順序問題了
- 依賴整合測試
- with
class
keyword - 類別實際上是一種特別的函數(functions)
- https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Classes
- 有著傳統 OO 特徵,心智負擔小
- 難以處理非同步建構任務
- Bundler 難以 chunk 分拆 function
- 這樣還是要實作全部的方法,累 🥲
class XXXDecorator implements IClass{
constructor(service:IService,instance:IClass){
this._service = service;
this._instance = instance;
// ....
}
operation(..args:any[]){
// 在參數動手腳 (Before)
const result = this._instance.operation(...args)
// 在回傳動手腳 (After)
}
// 還要繼續實作其它 method
...otherMethod(..args)
}
- closure based OO
Hook
in ReactComposable
function in Vue.js- https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Closures
- 方便處理 async 初始化動作
- 這樣寫比較能偷懶,只需處理要修飾的 method
function XXXDecorator(service:IService,instance:IClass):IClass{
const decoratorFn = (...args)=>{
// 在參數動手腳 (Before)
const result = instance.operation(...args)
// 在回傳動手腳 (After)
}
return {
...instance,
operation: decoratorFn
}
}
- 使用 JavaScript (預計實作)原生的 Decorators 語法
- TC39 ECMAScript Decorators 提案 終於進入 Stage 3.0 了
- TypeScript 5.0 預計實作 ECMAScript Decorators 提案
- [過時資訊] 是否应该在生產環境裡使用 TypeScript 的 Decorator?
- 上面這個問題其實也大幅影響到 Vue 3 開發時的 API 設計,從 Class based 轉向 Compsition API。 詳情
-
舉例:
- CacheDecorator -> 裝飾 Service 層 (API 層)
- 裝飾器就可以決定要從 Cache 拿還是真打 API
- CacheDecorator -> 裝飾 Service 層 (API 層)
-
In Functional Programing, maybe it could be replaced by function compsition.
-
最後選了 inversify 嘗試,但似乎不能 bind decorator,只能
手動
或是使用原生 Decorator
了 -
可以用
yarn dev
bundle 和跑跑看,但實際上跑不完
yarn
- package managerParcel
- BundlerTypeScript
Jest
withTs-Jest
- Test FrameworkPrettier
- Formatter
yarn install
- install packageyarn dev
- bundle and runyarn test
- running test