Kotlin 後端專案:為何 Service Layer 是不可或缺的一層?

14 分鐘閱讀

其實在學 Kotlin 的不是我,是另一位認識的網友。
我幫他 code review 之後發現他沒有做 service layer。

我的問句是一種 使用 AI 來產生詳細指引 的提問法,當資深人員在產出指南給新人時非常適合這種提示詞技巧。

琳 avatar

我正在學習規劃 kotlin 後端專案架構。請你說明為什麼不應該直接在 Controller 中使用 Repository,Service layer 帶來的好處為何。並且在最後說明從現有的「在 controller 中調用 Repository」的程式遷移到「擁有 service layer」的程式的 TODO 工作步驟。以 bullet point 撰寫工作步驟。

Felo Search avatar
Felo Search

在軟體架構設計中,分層是一種常見且重要的實踐,旨在提高程式碼的可維護性、可測試性和可重用性。

當 Controller 直接調用 Repository 時,雖然在簡單情境下看似便捷,但隨著應用程式複雜度的增加,會導致多種問題,例如業務邏輯分散、關注點混淆以及測試困難。引入 Service Layer 作為 Controller 和 Repository 之間的中介層,能夠有效地封裝業務邏輯、促進關注點分離,並簡化各層的職責,從而構建更健壯、更易於管理的應用程式。本報告將闡述不應直接在 Controller 中使用 Repository 的原因、Service Layer 帶來的好處,以及從現有架構遷移至包含 Service Layer 架構的具體步驟。

Controller、Service 與 Repository 的職責

在典型的三層式架構中,各層的職責如下:

為何不建議在 Controller 中直接使用 Repository

儘管在某些極其簡單的 CRUD 操作中,Controller 直接調用 Repository 看似可以減少程式碼量,但從長遠來看,這種做法會帶來以下問題:

Service Layer 的優勢

引入 Service Layer 可以帶來諸多好處,有效解決上述問題:

從「Controller 中調用 Repository」遷移至「擁有 Service Layer」的 TODO 工作步驟

將現有的直接在 Controller 中調用 Repository 的 Kotlin 後端專案遷移到包含 Service Layer 的架構,可以遵循以下步驟:

  1. 控制层(Controller) 服务层(Service) 持久层(Repository ... ↩2 ↩3

  2. Spring 練功場#2筆記-知識量爆發 - YungHsin ↩2

  3. Controller、@Service和@Repository注解详解 - CSDN博客

  4. Laravel中服务层(Service Layer)使用详解原创 - CSDN博客 ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9

  5. 【Spring Boot】第4課-實作三層式架構的Service 與Repository ↩2 ↩3

  6. 简单地聊一聊Spring Boot的构架 - 腾讯云 ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8

  7. 在Service层中进行验证(还是翻的) 转载 - CSDN博客

  8. Understanding the Service Layer in Software Architecture ↩2 ↩3 ↩4 ↩5 ↩6 ↩7

  9. Understanding the Service Layer in Software Architecture | by LadlaAqeel | Medium ↩2

  10. Service Layer Pattern in Java: Enhancing Application Architecture with Robust Service Layers | Java Design Patterns

  11. 控制层(Controller) 服务层(Service) 持久层(Repository ...

  12. 简单理解Repository层、Service层、Controller层 - CSDN博客

  13. Best Practices in Spring Boot: Avoid Injecting Repositories Directly into Controllers | by Vidushika Dasanayaka | Nerd For Tech | Medium ↩2 ↩3 ↩4 ↩5 ↩6 ↩7 ↩8 ↩9

  14. Best Practices in Spring Boot: Avoid Injecting Repositories ... ↩2 ↩3 ↩4

  15. Should I always use service, or can I use the repositories ...

  16. 【Spring Boot】第4課-實作三層式架構的Service 與Repository ↩2 ↩3

  17. Test Automation in Service Layer | Top 5 Benefits

  18. Do I need a service layer? - Coderanch

  19. SpringBoot的Controller,Service,Repository层的使用 - CSDN博客 ↩2 ↩3 ↩4 ↩5

  20. SpringBoot的Controller,Service,Repository层的使用-CSDN博客

  21. SpringBoot的Controller,Service,Repository层的使用 - CSDN博客 ↩2

  22. Is it a bad practice that controller uses repository directly?

  23. 控制器直接用repository 是不是不太好? : r/learnjava - Reddit

  24. 使用Hilt 插入依附元件| App architecture - Android Developers